C# Output XML from Linq to Response.OutputStream
Is there a simpler way to output a Linq to SQL table to XML (eventually to a web page?) Unfortunately, I am not using MVC, but I could put a reference to it in my aspx C# page.
I have this:
var myView = (from x in db.myTable
where x.Name.Contains("Bob")
select new person {Name = x.Name, Job = x.Job).Take(100);
and want to output something similar to this (doesn't have to be exact for now):
<?xml version="1.0" encoding="utf-8"?>
<myView xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<person><Name>Bob Smith</Name><Job>Machinist</Job></person>
<person><Name>Bob Smithers</Name><Job>Cartoonist</Job></person>
<person><Name>Rebob Wilson</Name><Job>Mason</Job></person>
</myView>
I tried doing this:
TextWriter myTW = new StreamWriter( Response.OutputStream, Encoding.UTF8);
XmlTextWriter xmlTW = new XmlTextWriter(myTW);
XmlSerializer myS = new XmlSerializer( typeof( person));
myS.Serialize( xmlTW, myView);
But I get a "Cannot serialize iQueryable". However, I tri开发者_如何学JAVAed ToArray, ToList, AsEnumerable, etc. and simply get "An error occured" with myS.Serialize().
Any thoughts? Hopefully there is a way like return XML(myView);
Try this:
var result = myView.ToArray();
var serializer = new XmlSerializer(result.GetType());
serializer.Serialize(Response.OutputStream, result);
精彩评论