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 extremely easy.
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.
XDocumentwill contain your entire XML document. You add
XAttributeobjects to your
XElementholds a single XML element. An
XElementobject can be added to an
XAttributecontains a single attribute name/value pair that is contained within an
XDocument is generated, a simple .ToString() will return the entire document to us in a printable format.
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!