This is a quick example of loading data into and XmlDocument and then extracting data using XPath. Each of those topics have books written on them and one can surely use this sample as a starting point for that learning.

Note the Xpath used does not demonstate the full capabilities of Xpath such as one can extract attributes off of nodes using the @ sign.

 1: XmlDocument xd = new XmlDocument();
 2:
 3: xd.LoadXml(
 4: @"<?xml version='1.0'?>
 5:     <Wrapper>
 6:         <myData>some stuff</myData>
 7:         <level access='t'>4</level>
 8:         <size>medium</size>
 9:    </Wrapper>");
 10:
 11: XmlNode node
 12:     = xd.SelectSingleNode(
 13:         "descendant::*[name(.) ='myData']");
 14:
 15: Console.WriteLine("Inner Text ({0}) Outer Xml {1}",
 16:                   node.InnerText,
 17:                   node.OuterXml);
 18:
  • Line 1 Create a new XmlDocument.
  • Line 3 Load the Xml from a string, other ways one could load from a file.
  • Line 11-13 We are interested in getting the first node encountered thats name is myData. By using the SelectSingleNode we can get just one.
  • Line 13 This is a generic Xpath that I like to use which can get information from the current node looked being looked at. What it is saying is, Looking at all the decendants of the current node, give me the node where the name found is myData.
  • Line 15 We are not checking to see if node is null. In normal code this is a no-no, check before usage!
  • Line 16 The actual data is store in the InnerText of the node, which we will extract.
  • Line 17 Sometimes we need the xml along with it, see below.

This is what the output looks like:

Inner Text (some stuff) Outer Xml <myData>some stuff</myData>

Share

Tags: ,