LINQ to XML techniques: building a basic XML document
September 9, 2016 Leave a comment
XML may have fallen out of use compared to JSON recently but it still has a couple of good features, such as schema and namespace support. It provides the basis for standards such as XHTML, SVG, MathML and many others. The web is full of resources that discuss the pros and cons of XML and JSON, here are a few of them:
- XML and JSON on StackOverflow
- Advantages of XML over JSON
- An alternative reading about why we should not compare XML and JSON
So from time to time you may still be exposed to XML in a .NET project. The System.Xml namespace offers classes with which you can build XML documents. Examples includes XmlDocument, XmlElement and XmlAttribute. However, there’s a more fluent and modern way of working with XML in code. LINQ to XML is located in the System.Xml.Linq namespace and it offers a very good library to build, modify and consume XML documents. Let’s start off with the most basic objects:
- XDocument: represents an XML document
- XElement: represents an element within a document such as a node
- XAttribute: represents an XML attribute
Here comes a short example code:
XDocument bandsDocument = new XDocument( new XElement("Bands", new XElement("Band", new XAttribute("genre", "rock"), new XElement("Name", "Queen"), new XElement("NumberOfMembers", 4)), new XElement("Band", new XAttribute("genre", "progressive"), new XElement("Name", "Genesis"), new XElement("NumberOfMembers", 5)), new XElement("Band", new XAttribute("genre", "metal"), new XElement("Name", "Metallica"), new XElement("NumberOfMembers", 4))));
The root of the document will be “Bands” which is given by the first XElement object in the XDocument constructor. Note how XDocument accepts a parameter array of objects which allows us to provide all the nodes of the document. XElement also accepts an array of sub-elements, so we can easily provide the constituent nodes and their attributes. It’s easy to get lost with all those brackets but here’s what the above code produces:
<Bands> <Band genre="rock"> <Name>Queen</Name> <NumberOfMembers>4</NumberOfMembers> </Band> <Band genre="progressive"> <Name>Genesis</Name> <NumberOfMembers>5</NumberOfMembers> </Band> <Band genre="metal"> <Name>Metallica</Name> <NumberOfMembers>4</NumberOfMembers> </Band> </Bands>
You can simply call bandsDocument.ToString() to see the resulting XML.
An additional benefit of building the XML document in code like above is that the code itself can be structured and indented in a way that represents the resulting XML document. In other words it’s easier for the developer to guess what the resulting XML document will look like.
That was easy and straightforward I hope. We’ll explore LINQ to XML on this blog in the coming months.
You can view all LINQ-related posts on this blog here.