LINQ to XML techniques: adding a declaration
September 16, 2016 Leave a comment
In this post we saw how to add a namespace to an XML document. A namespace in XML is similar to the namespace in a programming language. It helps to avoid name clashes among nodes that can have similar names, like “Customer” which is quite a common domain. The fully qualified name of a node will be the namespace and the node name.
In this post we’ll see how to add a declaration to an XML document.
An XML declaration declares that a document is an XML document. It also provides a couple of attributes:
- version: denotes the XML standard. This is a mandatory attribute and has only one possible value: 1.0
- encoding: the encoding such as UTF-8
- standalone: “yes” or “no” where yes means that the document has an internal document type declaration (DTD). No means that the document is linked to an external DTD
A well-formed XML document normally begins with a declaration.
The XDeclaration class represents an XML declaration and can be used in two ways. Here’s how to add the declaration to an XDocument directly:
XDocument bandsDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), 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)))); Debug.WriteLine(bandsDocument.Declaration + Environment.NewLine + bandsDocument.ToString());
Note how we had to tell the WriteLine method to explicitly print the declaration as well. XDocument.ToString omits the declaration for some reason. The above code produces the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <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>
The declaration can be added after creating the XDocument using the Declaration property of XDocument:
XDocument bandsDocument2 = 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)))); bandsDocument2.Declaration = new XDeclaration("1.0", "UTF-8", "yes");
You can view all LINQ-related posts on this blog here.