Xml handling using XmlDocument and Xpath

Posted by OmegaMan at August 8, 2007

Category: XML

Tags: ,

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();
 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>");
 11: XmlNode node
 12:     = xd.SelectSingleNode(
 13:         "descendant::*[name(.) ='myData']");
 15: Console.WriteLine("Inner Text ({0}) Outer Xml {1}",
 16:                   node.InnerText,
 17:                   node.OuterXml);
  • 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>


Leave a comment

(required) (will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Recent Comments

    Thanks for this simple yet delightful code....
    Hey guys I'm having the same problem as Netanel KL { “Error HRESUL...
    Soluciono el problema con el primero (First step solved it for me)....
    Thank you! I was looking for this. You save my day!...
    Thank you! This was a big help. My requirement was a little differen...
    Thanks, after a small path adjustment it worked for Visual Studio 2015...
    Good call!...
    Thank you .. this helped...
    How about when you have a long string with no space? I tried it and it...
    Thank you, I ran into this same issues with Visual Studio 2015 after i...
  • Categories

  • Tags

  • Meta