Sunday, May 24, 2009

Simple XPath Examples

Hi,
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'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>


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" + "']");

4 comments:

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();
XmlPersons1.Load(@"Persons.xml");

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 (http://wiki.magnolia-cms.com/display/WIKI/Hibernate%27s+Criteria-like+API+for+Magnolia-JCR)

anon_anon said...

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

http://vtd-xml.sf.net