Wednesday, 7 December 2016

35 C# XmlNode class

Working with the XmlNode class

In the previous chapter, we used the XmlDocument class to parse an XML file. A new class was introduced in the example, which is very essential to parsing XML with XmlDocument: The XmlNode class. The XML is basically parsed into an XmlNode which is the root element and then you can access the child elements using the ChildNodes property. However, the XmlNode class gives you access to a lot of other information as well, for instance the name of the tag, the attributes, the inner text and the XML itself. This chapter is a brief description of some of the more interesting aspects of the XmlNode class, which is important to know about because the XmlNode class is such a key concept when parsing XML with the XmlDocument class. In the following examples we will use the DocumentElement a lot, and while it is in fact of the type XmlElement, XmlElement does inherit from XmlNode, so it's essentially the same. 

The Name property will simply give you the name of the node. For instance, the following example will output the text "user":
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<user name=\"John Doe\">A user node</user>");
Console.WriteLine(xmlDoc.DocumentElement.Name);
Console.ReadKey();
The InnerText property will hold the text contained within the starting and the ending tag, like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<test>InnerText is here</test>");
Console.WriteLine(xmlDoc.DocumentElement.InnerText);
Console.ReadKey();
The InnerXml property is a bit like the InnerText property, but while InnerText will strip out any XML within it, the InnerXml property obviously won't. The following example should illustrate the difference:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<users><user>InnerText/InnerXml is here</user></users>");
Console.WriteLine("InnerXml: " + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine("InnerText: " + xmlDoc.DocumentElement.InnerText);
Console.ReadKey();
The OuterXml property is the same as the InnerXml, but it will include the XML of the node itself as well. The following example should illustrate the difference:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<users><user>InnerText/InnerXml is here</user></users>");
Console.WriteLine("InnerXml: " + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine("OuterXml: " + xmlDoc.DocumentElement.OuterXml);
Console.ReadKey();
We worked with attributes in the previous chapter, but here is another example:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<user name=\"John Doe\" age=\"42\"></user>");
if(xmlDoc.DocumentElement.Attributes["name"] != null)
    Console.WriteLine(xmlDoc.DocumentElement.Attributes["name"].Value);
if(xmlDoc.DocumentElement.Attributes["age"] != null)
    Console.WriteLine(xmlDoc.DocumentElement.Attributes["age"].Value);
Console.ReadKey();

No comments:

Post a Comment