Reputation: 2079
I have an xml of the following structure:
<Root>
<Sample>
<Materil material_class="book" />
<Book Name="harry" Price="8" />
<Book Name="small things" Price="9" />
<Book Name="snow" Price="10" />
</Sample>
<Commodity>
<Sample>
<Materil material_class="sub" />
<Book Name="sherin" Price="8" />
<Book Name="bigthings" Price="9" />
<Book Name="leopard" Price="10" />
</Sample>
<Commodity>
<Sample>
<Materil material_class="sub" />
<Book Name="azxcv" Price="86" />
<Book Name="ddddd" Price="79" />
<Book Name="qwert" Price="810" />
</Sample>
</Commodity>
<Commodity>
<Sample>
<Materil material_class="subtwo" />
<Book Name="ratnam" Price="86" />
<Book Name="shantharam" Price="99" />
<Book Name="da vinci" Price="10" />
</Sample>
</Commodity>
</Commodity>
</Root>
Is there a way to iterate this xml based on condition like,if the material_class = "sub"
, iterate the Book
tag below that and store the @Name
and @Price
. If the material_class = "book"
, iterate the Book
tag below that. Also i want to get the length of number of /Root/Commodity/Commodity
tags (in this case , it is two). Any help is appreciated. I am new to XPath.
Upvotes: 0
Views: 727
Reputation: 18064
To get the Book @Name
and @Price
for @material_class='sub'
or @material_class='book'
, use this XPATH
/Root[descendant-or-self::Sample or Sample[descendant-or-self::*]]//*[Materil[@material_class='sub' or @material_class='book']]/Book
OR
//Sample[Materil[@material_class='book' or @material_class='sub']]/Book
After loading this XPATH, to print the Name use @Name
and Price use @Price
To get the length of number of /Root/Commodity/Commodity tags, XPATH is
/Root/Commodity/Commodity
OR
//Commodity/Commodity
NodeList node = (NodeList) xpath.evaluate("/Root/Commodity/Commodity", xml, XPathConstants.NODESET);
count = node.getLength(); // OUTPUTS: 2
For your information, actually rendering XML through XSLT is much better performance and easier to implement.
Upvotes: 1
Reputation: 5145
<xsl:apply-templates select="//Sample[Materil[@material_class='sub']]/Book"/>
<xsl:apply-templates select="//Sample[Materil[@material_class='book']]/Book"/>
I do not have access to an XSL editor right now, so have not tested the above, but it will give you an idea. Select the Book, and constrain the Materil with the condition you want.
Upvotes: 0