Sunday, May 24, 2009

Simple XPath Examples

In this post i'll show some simple(but useful) XPath Examples
let's say that i have this xml file named 'Persons.xml':

<?xml version='1.0'?>


<Person Height="180">

<FullName>Yosi Havia</FullName>



<Person Height="177">

<FullName>Yosi Cohen</FullName>



<Person Height="169">

<FullName>Itay Cohen</FullName>




so, let's talk code lines:

//@@@ Select all the persons in 18 age
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age = '" + 18 + "']");

//@@@ Select all the persons with age greater than 17
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age > '" + 17 + "']");

//@@@ Select all the persons that contains Yosi in their names
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person/FullName[contains(.,'" + "Yosi" + "')]");

//@@@ Select all the persons with 180 height(attribute)
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[@Height = '" + "180" + "']");


Himanshu said...

1. Where did you get XmlPersons Object from?
2. Is this .NET specific code. Any clue if libraries in Java are so simplistic?

Yosi Havia said...

Hi Himanshu,
1. To get XmlPersons use:
XmlDocument XmlPersons1 = new XmlDocument();

2. I did'nt try it at java

Federico Grilli said...

@Himanshu: in Java there's a Criteria-like API to retrieve JCR nodes but it's Magnolia CMS specific (

dontcare said...

Nice article, btw, VTD-XML has the most adavnced xpath engine