Linq to Xml is a very succinct way to express Xml from linq queries.
Here is how you can build an Xml tree in LINQ to Xml (from Microsoft: https://msdn.microsoft.com/en-us/library/bb387089.aspx).
XElement contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144"),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);
Output:
<Contacts>
<Contact>
<Name>Patrick Hines</Name>
<Phone>206-555-0144</Phone>
<Address>
<Street1>123 Main St</Street1>
<City>Mercer Island</City>
<State>WA</State>
<Postal>68042</Postal>
</Address>
</Contact>
</Contacts>
Joseph Albahari's great c# bible C# 5.0 In a Nutshell has some great examples including a chapter on "Linq to XML". His free LinqPad application comes with some good examples like these ones below from chapter 10.
The examples below build XML directly from a Linq statements. You can see that it gives you more direct control over the output XML than direct serialization and simplifies creating more complex XML structures.
// Query Example 1
IQueryable<XElement> sqlQuery =
from c in Customers
select
new XElement ("customer", new XAttribute ("id", c.ID),
new XElement ("name", c.Name),
new XElement ("buys", c.Purchases.Count)
);
var customers = new XElement ("customers", sqlQuery);
// Query Example 2
new XElement ("customers",
from c in Customers
let lastBigBuy = (
from p in c.Purchases
where p.Price > 1000
orderby p.Date descending
select p
).FirstOrDefault()
select
new XElement ("customer", new XAttribute ("id", c.ID),
new XElement ("name", c.Name),
new XElement ("buys", c.Purchases.Count),
new XElement ("lastBigBuy",
new XElement ("description",
lastBigBuy == null ? null : lastBigBuy.Description),
new XElement ("price",
lastBigBuy == null ? 0m : lastBigBuy.Price)
)
)
)