Click here to Skip to main content
Click here to Skip to main content

Advanced XPath Analyzer

By , 30 Dec 2003
 

Introduction

This is an advanced version of the good XPath Analyzer done by Enrico Elizar Samuel (http://www.codeproject.com/aspnet/xpathanalyzer.asp). Advanced XPath Analyzer has been re-written in C# and supports namespaces resolution and navigation.

Notes about the code

The main difference from the original XPath Analyzer is that you can navigate into an XML document using qualified names. It is also possibile to have a default namespace in the XML document. In this case a the namespace prefix will be def, so that you can refer to it in your xpath expression.

Let's say that, for example, we have an XML document that looks like this one:

<?xml version="1.0" encoding="utf-8"?>
<items link="~/Html/Default.htm" xmlns=http://site/menu 
    xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance 
    xsi:schemalocation="http://site/menu menu.xsd">
    <item title="Products" link="#">
        <item title="Product 1" link="#"/>
        <item title="Product 2" link="#"/>
        <item title="Product 3" link="#"/>
        <item title="Product 4" link= "#"/>
    </item>
    <item title="Services" link="#">
        <item title="Service 1" link="#" />
        <item title="Service 2" link="#" />
    </item>
    <item title="People" link="#"/>
    <item title="Opening Hours" link="#"/>
    <item title="Prices" link="#"/>
    <item title="Contacts" link="#"/>
</items>

That is, as you may have guessed, the navigation menu of a simple website. If you need to get the Product 3 link, you should write an XPath query like:

/items/item[@title='Products']

but this query won't give any result! This because you need to specify that the elements items and item belongs to the default namespace http://site/menu as it really is, otherwise the parser will understand that they aren't associated with any namespace.
So, the correct query is:

/def:items/def:item[@title='Products']

in order to run correctly this query you first need to define that the prefix def points to the default namespace URI. With the Advanced XPath Analyer you can just manually add the namespace or ask to it to detect it automatically, but what really happens behind the scenes?
Three steps are needed to make the XPath query run without errors:

  1. Define an XmlNamespaceManager with all the needed namespaces
  2. Create an XPathExpression that contains the relative XPath Expression
  3. Assign the created XmlNamespaceManager object to that XPathExpression

That, in pratice, means to write something like:

XmlNamespaceManager namespaceManager = 
    new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace(prefix, uri);
XPathExpression expression = navigator.Compile(xpathQuery);
expression.SetContext(namespaceManager);

Where prefix and uri are the variables that contains the relative values, and navigator is the XPathNavigator that you're using to navigate through the document.

Using the program

You have to specify the XML source file (which can be a file on your hard disk or a file somewhere in the web) and then the XPath Query you'd like to test. You can also specify a SQLXML url so that you can test your SQLXML Queries. If your XML uses namespaces you have to add it in the left panel so that you can use them in your XPath Query, otherwise you can detect it automatically, clickin' on the Detect Namespace button. Of course remember to do this before you analyze the XPath Query!

Location of XML document:

http://localhost/nwind/schema/schema1.xsd/Employees?root=root

XPath query:

//root/Employees

History

  • v 1.0: First version
  • v 1.1: Added automatic namespace discovery

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

ManOwaR
Web Developer
Italy Italy
Member
Born in 1977, works as a freelancer, focusing on Database / Software Architecture.
In the free time writes articles for two of the major Italian programming magazines (Computer Programming and VBJ) and also develops nice and useful programs.
His major interests and skills are the .NET framework (C# in particular) and SQL Server.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionXPath Query doesn't work if you have multi-level namespace without prefix. [modified]membermaggiesrara3 Oct '07 - 6:48 
<a xmlns="namespace1">
   <b xmlns="namespace2">
      <c xmlns="namespace3">
         value
      </c>
   </b>
</a>
 
if I do "/def:a/def:b/def:c", it doesn't return "value"
GeneralSugestionmemberAdrian Bacaianu8 Sep '04 - 21:27 
Nice will be to have 2 text areas, with XML and XSL string data, to be possible to easy make a copy/paste.
 
To save all time xml data to a file and ftp to the web server is not possible all the time to a non develop server, also istime consuming.
 
Adrian Bacaianu
GeneralNamespace problemmemberCharles E. Wagner Jr.23 Dec '03 - 10:51 
When using the bookstore.xml from your download I cannot get this XPath statement to show me the ISBN attribute.
 
//book/@bk:ISBN
 
it works in everyother xml program I have...
 
why does the above statement not work?
 
Charles E. Wagner Jr.
GeneralRe: Namespace problemmemberManOwaR23 Dec '03 - 21:58 
Probably you haven't specified the right URI for the namespace "bk".
 
In the bookstore.xml example, the "bk" namespace refers to "urn:samples". You have to add it to the namespace window before clicking on "Analyze".
You can add a new namespace through the "New Namespace" window, positioned on the right.
Once done that it will work fine, giving you 4 nodes.
 

 
-=ManOwaR=-
 

QuestionWhat's advanced?memberStephane Rodriguez.17 Dec '03 - 1:23 
No pun intended. I don't see what's advanced here. The Xpath engine is provided by the BCL anyway, and unless I have missed something, you are not adding features to it.
 
For one advanced, take a look at Visual XPath[^] : code generator, and also creates Xpath queries based on interactive node selection. Even though the interactive mode will never build complex query by itself, it's certainly a good tool to ride the horse.
 
My 0.5 cent.

 

-- modified at 9:42 Saturday 8th October, 2005
AnswerRe: What's advanced?memberManOwaR17 Dec '03 - 2:23 
Advanced means only that this tool is a version of the XPath Analyzer with some features added.
 
-=ManOwaR=-
 

GeneralRe: What's advanced?sitebuilderUwe Keim17 Dec '03 - 22:06 
Yes, and he asked WHICH features you added.
 
--
- Free Windows-based CMS: www.zeta-software.de/enu/producer/freeware/download.html
- See me: www.magerquark.de
 

GeneralRe: What's advanced?memberManOwaR17 Dec '03 - 22:15 
As i wrote in the article above, as you may have read, i hadded the namespace navigation support which was missing in the original project.
 
-=ManOwaR=-
 

GeneralRe: What's advanced?memberDaniel Cazzulino22 Dec '03 - 14:41 
And you call "advanced" to that??!!??!?!?
 
Daniel Cazzulino
weblogs.asp.net/cazzu
 
Coauthor of:
Beg. C# Web Apps
ASP.NET Components Toolkit
Beg. Web Programming w/VB.NET & VS.NET
Pro ASP.NET Server Controls w/C#
GeneralRe: What's advanced?memberManOwaR22 Dec '03 - 20:48 
Again i say that i called it advanced just to mean that is something MORE than the original XPath Analyzer. Is that clear?!? Hopefully yes.
 
Than, call it whatever you like, i realased this program just 'cause i think can be useful to other people, surely not for having trouble with who don't like its name.
If you don't like my realase or you don't like the name just write another url in your address bar and forget about it.
 
In addition, if you're so smart, do something REALLY advanced so what you can show what an advanced program really is, and maybre realease it to the community so that it can be of some help to everyone.

 
-=ManOwaR=-
 

GeneralRe: What's advanced?memberDaniel Cazzulino22 Dec '03 - 23:59 
I was just arguing that "advanced" stuff like this is what lowers the general quality of CodeProject. If you're about to release something, make it something that doesn't only avoids me a couple lines of code. That's trivial and I wasted my time by looking at your "advanced" code only to realize it wasn't. I'm losing it now answering you because I hope one day nobody will polute CodeProject with trivial stuff just for the sake of appearing in a URL.
An I DID release important (and I believe *advanced*) stuff to the community:
- An Schematron XML validation language implementation in C#
- A code generator based on proven design pattens and XML
- A WMI data provider for .NET
- A data layer component based on XML and XPath
- Regularly I share useful (mostly *advanced*) code in my weblog
 
All the code I share, being sufficiently big to justify it, is released on Sourceforge in my (and 48 more developers) NMatrix opensource project as separate modules.
I believe some of this work is helping people. Do a search on the web for my name and you'll find that I ENJOY helping.
 
Daniel Cazzulino
Beg. C# Web Apps
ASP.NET Components Toolkit
Beg. Web Programming w/VB.NET & VS.NET
Pro ASP.NET Server Controls w/C#
GeneralRe: What's advanced?memberManOwaR23 Dec '03 - 7:59 
Hey man you're missing something...read this snippet take fome the CodeProject presentation: "The Code Project is a community of Visual Studio .NET developers joined together with a common goal: To learn, to teach, to have fun programming. Developers from all over the world come together to share source code, tutorials and knowledge for free to help their fellow programmers."
 
So, in the CodeProject site you'll find anything, not only what *YOU* like...i release code and articles just cause i think it will help other people that got stuck in problems similar to the one i found, so that i can be of some help to them, no matter how "advaced" this help could be...i really do not have any kind of interest of just appearing in a URL...my aim is to help other programmers as others did for me, since i believe in co-operation...in addition you should be smart enough to understand that "advanced" has a very relative meaning for everyone.
 
Btw, check you're site at http://nmatrix.com.ar, since, though it is a very advanced project, it seems to produce a very simple result: "Server Error in '/' Application."
 
This is my final word to this little "flame" since i do not want to spend any other minute on this, and, in addition, i don't think that other people are interested in this discussion. I just invite you to respect more the work of other programmars: if you don't like what they publish just pass by.
 
Have a nice Christmans.
 
-=ManOwaR=-
 

GeneralRe: What's advanced?memberDaniel Cazzulino23 Dec '03 - 9:41 
I've to admit it, you have a point regarding the general goal of CodeProject. And you're also right about simply ignoring content that doesn't appeal to me.
I didn't mean to be rude, I apologize for that. The reason for my reaction is that I think there isn't any fun or teaching in "forking" someone else's article, making a new one that doesn't even bother to explain anything and doesn't even reach 1 page of text, calls itself "advanced" and only adds marginal (what? 10 lines of code? you didn't even bother to explain that!) value to the original.
This is SO contrary to the principles of community and opensource that it touched me, nothing more. In an OS-friendly way, you would have discussed your ideas on how to advance the example, and contribute your extensions to him.
About my site, it's on a dynamic IP, and from time to time, it fails to syncronize and someone else's site is failing (I guess). That's why I send people to the SourceForge site, instead of mine.
And any of those subprojects have nothing to do with web applications, so "my" site failing isn't a proof of anything. But's that another issue.
I'd just like you to think about what does learning, teaching and having fun means.
 
Anyways, Manowar rocks (the latest album is certainly a strange one, but what the hell, they can do whatever they want at this point! they still are the kings of metal Smile | :) ).
I do wish you a nice xmas. If I started this thread sort of violent, I'm sorry.
 
Daniel Cazzulino
My Weblog
 
Coauthor of:
Beg. C# Web Apps
ASP.NET Components Toolkit
Beg. Web Programming w/VB.NET & VS.NET
Pro ASP.NET Server Contro
GeneralRe: What's advanced?memberManOwaR26 Dec '03 - 0:02 
Well, at the end we found ourself on the same side of the river. I'm happy about that! I know that i haven't explained deeply the changes i've done to the original software, but, belive me, is just because i haven't got the time to do it. I've found the original XPath Analyzer, saw that it could be useful to me with some little changes (the namespace resolution above all) and, once done the modification i needed, i decided to realease it to the community so that it may be of help to other people having the same needings. I've found that what we may consider unuseful or worth nothing, can be really useful to other man in a way that we can't imagine!
 
Btw, i've seen your blog and added it to my Rss Aggregator Smile | :)
 
Do you like Manowar too? I really *love* their music! I've been to all concerts they've done here in Italy Smile | :) ..it's incredible how they still be the kings of metal! (You know, they're no more so young Big Grin | :-D )
 
Have a happy New Year!
 

 
-=ManOwaR=-
 

AnswerRe: What's advanced?memberCharles E. Wagner Jr.23 Dec '03 - 10:50 
When using the bookstore.xml from your download I cannot get this XPath statement to show me the ISBN attribute.
 
//book/@bk:ISBN
 
it works in everyother xml program I have...
 
why does the above statement not work?
 
Charles E. Wagner Jr.
GeneralRe: What's advanced?memberDaniel Cazzulino6 Jan '04 - 5:35 
I haven't seen the download, but I bet your prefixes are wrong. By default, elements (and their children) are namespace-qualified (when an xmlns is used) but attributes are not, therefore, I believe your XPath should be:
 
//bk:book/@ISBN
 
Daniel Cazzulino
My Weblog
 
Coauthor of:
Beg. C# Web Apps
ASP.NET Components Toolkit
Beg. Web Programming w/VB.NET & VS.NET
Pro ASP.NET Server Contro

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 31 Dec 2003
Article Copyright 2003 by ManOwaR
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid