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.
- 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>