Search by xpath

Let's assume this is xml:

<lib>
<books type="paperback" name="A" />
<books type="pdf" name="B" />
<books type="hardbound" name="A" />
</lib>

      

What would be the xpath code to find a book like = "paperback" and name = "A"? TIA.

Currently my code looks like this:

   import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;

public class demo {

  public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = 
    DocumentBuilderFactory.newInstance();
          domFactory.setNamespaceAware(true); 
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("xml.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
       // XPath Query for showing all nodes value
    String version="fl1.0";
    XPathExpression expr = xpath.compile("//books/type[@input="paperback"]/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
     System.out.println(nodes.item(i).getNodeValue()); 
    }
  }
}

      

+2


source to share


3 answers


/lib/books[@type='paperback' and @name='A']

      

Take a look here if you are struggling with the xpath syntax it has some nice examples.



Also, if you just need help with XML in general and related technologies, check out the tutorial here

+2


source


Right now you seem to be looking for something like <book><type input="paperback"/></book>

, which is clearly not the case. Your xpath expression should be something like // books [@type = "paperback" and @ name = "A"] / text ()



0


source


The answers above are good ... I wanted to contribute. The best xpath tutorial I've seen is here .

0


source







All Articles