Generating an XML Document Using LINQ to XML
In the past, programmaticly creating XML documents in any programming language was extremely tedious and error-prone and .NET was no exception. Fortunately, LINQ remedied this for us in .NET 3.0.
In this post, I will demonstrate how mind-numbingly easy it is to create an XML document using LINQ to XML. Once you do this, you will never want to go back to the old ways of generating XML again.
Let's start by creating an XML document that contains all of the processes a system is running. Fortunately for us, LINQ makes this straightforward.
private static XDocument GetProcesses() {
return new XDocument(
new XElement("Processes",
from p in Process.GetProcesses()
orderby p.ProcessName ascending
select new XElement("Process",
new XAttribute("Name", p.ProcessName),
new XAttribute("ProcessID", p.Id))));
}
Easy, right? Notice how LINQ even allows us to order the process by their IDs in a way that is easy to read and understand.
Now, if you are used to generating XML documents the old C# 2.0 way then this should be even more exiting because this same bit of functionality would take about four times the amount of code to accomplish. These new LINQ classes allow us do do things much more efficiently and succinctly. Let's dive in to them and learn how they work.
**[XDocument]**
will contain your entire XML document. You addXElement
andXAttribute
objects to yourXDocument
.**[XElement]**
holds a single XML element. AnXElement
object can be added to anXDocument
or anotherXElement
object.**[XAttribute]**
contains a single attribute name/value pair that is contained within anXElement
object.
Once the XDocument
is generated, a simple .ToString() will return the entire document to us in a printable format.
XDocument xdoc = GetProcesses();
Console.WriteLine(xdoc.ToString());
If you run this on your machine, you should get something like this:
I uploaded this sample project to my Github account if you want to use it to help you learn these concepts better. The project is released under the Open Source Public License which means you can use it for free in any one of your projects without having to worry about licensing or attribution. Enjoy!
Subscribe for Free
Want to stay ahead of the curve? Subscribe now to receive the latest updates, actionable insights, and thought-provoking ideas around business, technology, and leadership straight to your inbox.