Useful Tool Xpather

time to read 5 min | 923 words

I found this nice utility at PerfectXml, it allows you to run ad-hoc XPath queries against any xml document and report both the results and the type of the result.

The only addition that I've made was to add namespace support, you can use it this way:
xpather hibernate.cfg.xml //nh:session-factory/ nh=urn:nhibernate-configuration-2.0

I've found it very useful for small testing of xpath expressions, mainly because I uses XPath every once in a while, so I tend to forget the particulars.

using System;
using System.Xml;
using System.Xml.XPath;
class Class1
{
   [STAThread]
   static void Main(string[] args)
   {
      if(args.Length < 2)
      {
         Console.WriteLine("Incorrect number of parameters.");
   Console.WriteLine("Usage: xpather <filename> <xpath> <ns-prefix=namespace> <ns-prefix=namespace>...");
         return;
      }
      try
      {
         //Load the XML document

         XmlDocument doc = new XmlDocument();
         doc.Load(args[0]);
         //Create XPathNavigator

         XPathNavigator xpathNav = doc.CreateNavigator();
  XmlNamespaceManager nsMgr = new XmlNamespaceManager(xpathNav.NameTable);
   
   for(int i=2;i<args.Length;i++)
   {
   string[] tmp= args[i].Split('=');
   if(tmp.Length==2)
   {
    nsMgr.AddNamespace(tmp[0],tmp[1]);
   }
   }
   
         //Compile the XPath expression

         XPathExpression xpathExpr = xpathNav.Compile(args[1]);
   xpathExpr.SetContext(nsMgr);
         //Display the results depending on type of result

         switch(xpathExpr.ReturnType)
         {
            case XPathResultType.Boolean:
               Console.WriteLine("Boolean value: {0}"
                  xpathNav.Evaluate(xpathExpr));
               break;
            case XPathResultType.String:
               Console.WriteLine("String value: {0}"
                  xpathNav.Evaluate(xpathExpr));
               break;
            case XPathResultType.Number:
               Console.WriteLine("Number value: {0}"
                  xpathNav.Evaluate(xpathExpr));
               break;
            case XPathResultType.NodeSet:
               XPathNodeIterator nodeIter =  xpathNav.Select(xpathExpr);
               Console.WriteLine("Node-set count: {0}"
                  nodeIter.Count);
               while(nodeIter.MoveNext())
                  Console.WriteLine(nodeIter.Current.Value);
               break;
            case XPathResultType.Error:
               Console.WriteLine("XPath expression {0} is invalid."
                  args[1]);
               break;
         }
      }
      catch(Exception exp)
      {
         Console.WriteLine("Error: " + exp.ToString());
      }
  }
}