使用xpath检索xml节点值

时间:2014-07-08 05:59:41

标签: java xml xpath xml-parsing

这是我的xml文件:bookstore.xml,我想要做的是我提供xpath作为输入,它应该给我它的节点值。但它给了我空值。

    <?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

这是java代码:

public class XmlParserUsingXpath {


        public void xmlParser(XPathExpression xpathexp) throws ParserConfigurationException, XPathExpressionException{


            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder dbuilder = factory.newDocumentBuilder();

            Document doc=null;

            try {
                 doc= dbuilder.parse(new FileInputStream("D:\\Bookstore.xml"));

            } catch (SAXException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();
            }

            doc.getDocumentElement().normalize();

            Object result = xpathexp.evaluate( doc, XPathConstants.NODESET );

            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i));
            }

        public static void main(String[] args){

            XmlParserUsingXpath o1= new XmlParserUsingXpath();

            XPath x=XPathFactory.newInstance().newXPath();

            System.out.println("Enter the Xpath Expression : ");

            Scanner sc= new Scanner(System.in);

            String scan= sc.nextLine();

            try {

                o1.xmlParser(x.compile(scan));

            } catch (XPathExpressionException | ParserConfigurationException e) {

                e.printStackTrace();
            }

        }



}

现在当我提供“//book”作为输入时,它给了我

[book: null]
[book: null]
[book: null]
[book: null]

"/bookstore/book[3]/author“会给出

[author: null]
[author: null]
[author: null]
[author: null]
[author: null]

2 个答案:

答案 0 :(得分:0)

我只是对角线阅读你的帖子但是尝试:

factory.setNamespaceAware(false);

答案 1 :(得分:0)

变化:

        Object result = xpathexp.evaluate( doc, XPathConstants.NODESET );

TO

        Object result = xpathexp.evaluate( doc, XPathConstants.NODE );