Reputation: 10291
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
Upvotes: 0
Views: 413
Reputation: 4051
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>
Upvotes: 1
Reputation: 292675
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)));
}
Upvotes: 7