LINQ to XML is a simple toolset that allows developers to easily interact with XML, whether it be in file form of on the wire in string form.
Write to an XML file
There are a few methods within the System.Xml.Linq namespace which make this interaction a breeze. The four main ones are:-
- XDocument – Method which creates the XML document
- XDeclaration – Allows you to set the declaration at the top of the file.
- XElement – Creates a hierarchical element structure
- XAttribute – Creates any attributes related to an element.
The following code shows a very simple way to generate an XML document for members of a club.
This would generate this XML file.
Reading from an XML file
Firstly use the Load method of the XDocument class, then a simple LINQ query will return all elements within the root element like this.
This query lists all the elements called ‘member’ within the root. Then for each member element it will again for each through for any elements within those. In our example the members full name is located there, so a simple value output will write the data to the console.
You can still use var for the query, but during running of the code it is possible to determine the resultant type.
This shows that it is of type XElement and that it is enumerable so you can change var to IENumerable<XElement> to give the code more meaning.