0

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 tried ToArray, ToList, AsEnumerable, etc. and simply get "An error occured" with myS.Serialize().

Any thoughts? Hopefully there is a way like return XML(myView);

1 Answer 1

2

Try this:

var result = myView.ToArray();
var serializer = new XmlSerializer(result.GetType());
serializer.Serialize(Response.OutputStream, result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.