Working with the XmlNode class
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();
Having problems with this chapter? Ask in our forums!
Could this article help your friends? Please help us to help them by sharing it on Facebook or Twitter: