MyTechFinds.com

  • Increase font size
  • Default font size
  • Decrease font size
Home Articles Software Development ASP.NET Some useful Xpath expressions

Some useful Xpath expressions

E-mail Print PDF
Here are some useful Xpath expression which were a little hard to figure out for a newbie like me so I am making an attempt to document them. Here are 2 of them,
  1. Get unique values using xpath
  2. Get leaf node only using xpath
Here is my input XML that I want to parse
<?xml version="1.0" standalone="yes"?>
<folder fname="data">
 <file feature="Catalog Home Applet" build="2.0.442.0" />
 <file feature="Devportal" build="2.0.442.0" />
 <file feature="Client" build="2.0.449.0" />
 <file feature="Client" build="2.0.448.0" />
 <file feature="SP Potral" build="2.0.441.0" />
 <file feature="GHx" build="2.0.441.0" />
 <file feature="Storage" build="2.0.442.0" />
</folder>


I want to fetch or retrieve unique build numbers from above XML using xpath, it is very clear that i can not use a simple xpath expression like
/folder/file[@build]

This will return all the build numbers. So clearly I need to put some comparison logic to get unique build number values. Simple way is to use xpath axis called preceding. This axes will return all the preceding nodes that appear in that XML document before the current one,
/folder/file[not(@build = preceding::file/@build)]

But this may be overkill or may sometimes return results that you are not expecting as preceding will look through the entire document that appears before that node and not just at that level. If you want to query only on the current level, you should use another xpath axis called sibling, to be specific - following-sibling and preceding-sibling. The xpath will like this
/folder/file[(not(@build = following-sibling::file/@build and @build = preceding-sibling::file/@build)]

The above expression seems to be complete but has a flow, if you run it over above XML, it will not return the build number for feature=devportal. Why? because that build number appears on both sides of that node. To save this, you can add another condition and your final expression will be,
/folder/file[(not(@build = following-sibling::file/@build and @build = preceding-sibling::file/@build) or @build]


Getting leaf nodes only using xpath can be done by yet another xpath axis called Child. This is how it can be done,
//TestList[count(child::*/child)=0]

( 0 Votes )
Comments
Search
Only registered users can write comments!

!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."

Last Updated on Friday, 26 March 2010 13:44  

Our valuable member Ajay Majgaonkar has been with us since Thursday, 23 April 2009.

Show Other Articles Of This Author

Software Development

Login

Like it? Share it!


Search

Polls

Which of the following are characteristics of testable software?
 

MyTechFinds

Advertisement

Help us
We have 2 guests online