tags:

views:

126

answers:

2
+2  Q: 

Search in xpath

Suppose this is the xml:

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

What will be the xpath code to search for book of type="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()); 
    }
  }
}
A: 

Right now you seem to search for something like <book><type input="paperback"/></book> which clearly is wrong. Your xpath expression should probably be something like //books[@type="paperback" and @name="A"]/text()

pafcu
Since the `books` elements have no conente, `text()` will give you nothing.
Thank you everyone who contributed to this thread.
fixxxer
+2  A: 
/lib/books[@type='paperback' and @name='A']

Have a look here if you're struggling with xpath syntax, it has a few nice examples.

Also, if you just need help with XML in general and related technologies, have a look at the guide here

Fiona Holder
@Fiona: I went through the code, but still a bit confused. If I need to search for "paperback" and retrieve corresponding name, can u tell me the code for the same?
fixxxer
/lib/books[@type='paperback']/@name
flybywire
One more, Since the type attribute differs in every tag in the above XML. Can we hold the value of Type in a String variable and substitute it in the xpath search variable?
fixxxer
I'm not quite sure that I understand your question, but you can definitely construct the xpath expression in Java and concatenate in a string variable, yes.
Fiona Holder
I want to create a String variable "type" and set it with the type of book(paperback, pdf et al) and use the variable in the xpath search.String TYPE="pdf"; /lib/books[@type='*insert TYPE here']/@name.Would this be correct?
fixxxer
Yeah, so you could do String type="pdf"; and then String xpath = "/lib/books[@type='" + type + "']/@name";
Fiona Holder
Thanks Fiona, that completely solved my problem!
fixxxer