Xml – Creating XML from a LINQ result

linqxml

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

Best Solution

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)));
    }