tags:

views:

55

answers:

3

If I've used LINQ to retrieve results from the database, is there a way that I can automagically get this to generate XML?

For example:

DataClasses1DataContext db = new DataClasses1DataContext(C_CONN_STRING);
var q = from stock in db.GetTable<Stock>()
        where stock.Group == 1
        select stock;

foreach(Stock s in q)
{
     //automatically create XML document here?
}

Sorry if this is such a really basic question, any help appreciated

+5  A: 

We don't know the exact content of your Stock object, and we don't know the form of the XML you want to generate, so this is just a wild guess...

    DataClasses1DataContext db = new DataClasses1DataContext(C_CONN_STRING);
    var q = from stock in db.GetTable<Stock>()
            where stock.Group == 1
            select stock;

    XDocument doc = new XDocument();
    foreach(Stock s in q)
    {
        doc.Add(
            new XElement("Stock"
                new XAttribute("Group", stock.Group),
                new XAttribute("Product", stock.Product),
                new XAttribute("Quantity", stock.Quantity)));
    }
Thomas Levesque
Ahh, you were faster... :)
Philippe
A: 

Look into XMLTextWriter then?

AKofC
-1: `XmlTextWriter` should no longer be used directly. Instead, `XmlWriter.Create` should be used.
John Saunders
+1  A: 

You could use VB to do that, as it supports XML literals in code.

If you have to go for C#, you can use XElement (example taken from C# in Depth):

var users = new XElement("users",
    from user in SampleData.AllUsers
    select new XElement("user",
        new XAttribute("name", user.Name),
        new XAttribute("type", user.UserType))
);

Which will produce something like this:

<users>
    <user name="Tim Trotter" type="Tester" />
    <user name="Tara Tutu" type="Tester" />
    <user name="Deborah Denton" type="Developer" />
    <user name="Darren Dahlia" type="Developer" />
    <user name="Mary Malcop" type="Manager" />
    <user name="Colin Carton" type="Customer" />
</users>
Philippe