简体   繁体   中英

xpath based on condition in java

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.

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

JAVA:

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.

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM