Using XPath

Posted by lorenb on 8/27/2004 in projects |

I’m just doing some work on sussen-sensor.

So say you have a large and complex XML document (i.e. OVAL definitions) and you need to find various pieces of information. You need to query the XML without having to go through all the nodes to find what you are looking for.

Enter XPath. You can make queries kind of like how you use SQL to query a database. Here is an example:


using System;
using System.Xml;
using System.Xml.XPath;

class MainClass {
        public static void Main (string[] args)
        {

         string xmlFragment = "< ?xml version='1.0'?>" +
             "<root>" +
             "<definition>Vulnerability A</definition>" +
             "<definition>Vulnerability B</definition>" +
             "<definition>Vulnerability C</definition>" +
             "<definition>Vulnerability D</definition>" +
            "</root>";

             XmlTextReader reader = new XmlTextReader(xmlFragment,  XmlNodeType.Element,null);

                // Instantiate an XPathDocument using the
                XmlTextReader.XPathDocument xpathDoc = new XPathDocument(reader, XmlSpace.Preserve);

                // get the navigator
                XPathNavigator xpathNav = xpathDoc.CreateNavigator( );

                // find all "definition" tags
                string xQuery = "//definition";

                // get the nodeset from the query
                XPathNodeIterator xpathIter = xpathNav.Select(xQuery);

                // write out the nodes found
                while(xpathIter.MoveNext( )) {
                        Console.WriteLine(xpathIter.Current.Value);
                }

                reader.Close( );
        }
}

Copyright © 2004-2010 LB Technology Services Blog All rights reserved.
Desk Mess Mirrored v1.7 theme from BuyNowShop.com.