在xpath中搜索

时间:2009-09-22 06:31:37

标签: java xpath

假设这是xml:

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

搜索type =“paperback”和name =“A”的书的xpath代码是什么? TIA。

目前我的代码如下:

   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()); 
    }
  }
}

3 个答案:

答案 0 :(得分:2)

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

如果您在使用xpath语法时遇到问题,请查看here,它有一些不错的示例。

另外,如果您只是需要有关XML和相关技术的帮助,请查看指南here

答案 1 :(得分:0)

现在你似乎在寻找像<book><type input="paperback"/></book>这样明显错误的东西。您的xpath表达式应该类似于// books [@ type =“paperback”和@ name =“A”] / text()

答案 2 :(得分:0)

上面的答案很好......我想贡献一份资源。我见过的最好的xpath教程是here