Tuesday, May 25, 2004

XPQ

Since Eric mentioned me, I feel all this pressure to post something cool and C#-related. OK, here's a neat little number:


public class App {
  const string USAGE = @"Usage: xpq <xpath> <input>"; 
  public static void Main(string[] args) {
   
if (args.Length != 2) {
     
Console.WriteLine(USAGE);
     
return;
   
}

   
XPathDocument doc = new XPathDocument(args[1]);
   
XPathNavigator nav = doc.CreateNavigator();

   
object o = nav.Evaluate(args[0]);

   
if (o is XPathNodeIterator) {
     
XPathNodeIterator iter = o as XPathNodeIterator;
     
while (iter.MoveNext()) {
       
Console.WriteLine(iter.Current.Value); 
      
}
   
}
   
else {
     
Console.WriteLine(o);
   
}
  }
}


What does it do? It lets you run XPath queries against files from the command line. I call it XPQ for XPath Query. So, for example, I can print the number of “foo” nodes in a doc by running:


   xpq count(//foo) doc.xml


Or I can print the value of every “bar” attribute in a document by running:


  xpq //*/@bar doc.xml


The way it works is by taking advantage of the XPathNavigator.Evaluate method, which runs the supplied XPath expression and returns an object. The type of the object you get back depends on the expression you provide. If the XPath expression evaluates to a number, you get a double. If it evaluates to a string, you get a string. And if it evaluates to a identify more than one node in the document, you get an XPathNodeIterator.


I'm sure there are 999 tools out there that do all this and more, but I love that the framework lets you do so much with just a few lines of code. And this one covers about 90% of the cases where I just need to know something quick about an XML document.

8 comments:

  1. What? You mean we actually have to compile it ourself? ;)

    ReplyDelete
  2. Nope, I couldn't wait to try it so I did it for you. Just follow the yellow brick road to your Solution!

    http://weblogs.asp.net/jtobler/archive/2004/05/27/143355.aspx

    ;P

    ReplyDelete
  3. Ah, the magic of open source.

    ReplyDelete
  4. I added a hack to add support for namespaces. It's in a post on my blog at http://sandspace.com/blog/posts/249.aspx. (I wonder why the trackback doesn't show up here?)

    ReplyDelete
  5. Ah, there's the trackback. Now I wonder why it took so long to show up? Time to find out how trackbacks work. Sorry for the comment spam.

    ReplyDelete
  6. No idea from my side why it took a while, but I don't have much control over this server. :p

    ReplyDelete
  7. Earlier today, I had a need for an XPath evaluator. I had an enormous XML document that I wanted to execute an XPath query against. I turned to Google... surprisingly enough, this appears to be very uncommon. I found only...

    ReplyDelete