0

我有一个xml

<?xml version="1.0" encoding="UTF-8"?>
<information>
  <person id="1">
  <name>Deep</name>
  <age>34</age>
  <gender>Male</gender>
  </person>

 <person id="2">
  <name>Kumar</name>
  <age>24</age>
  <gender>Male</gender>
  </person>

  <person id="3">
  <name>Deepali</name>
  <age>19</age>
  <gender>Female</gender>
  </person>

  <!-- more persons... -->
</information>
DocumentBuilderFactory domFactory = DocumentBuilderFactory
                .newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("persons.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        XPathExpression expr = xpath.compile("//information/person[0]/name/text()");

        Object result = expr.evaluate(doc, XPathConstants.NODE);
        Node node = (Node) result;
        System.out.println(node.getNodeValue());

我需要提取我尝试上述代码的第一个人的名字,它给出了异常,任何人都可以帮助我,

更新异常

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to javax.xml.soap.Node
    at xml.main(xml.java:33)

更新的答案

XPathExpression expr = xpath.compile("//information/person[1]/name");

        String str = (String) expr.evaluate(doc, XPathConstants.STRING);

        System.out.println(str);
4

2 回答 2

1

XPath 索引从基数 1 开始,而不是大多数人认为的 0,因此 person[0] 不会返回任何内容。将您的 XPath 更改为//information/person[1]/name/text() 您还可以指定位置以避免完全使用静态数字://information/person[position()=1]/name/text()

或者//information/person[@id='1']/name/text()如果您需要 id。

于 2012-04-11T18:12:07.243 回答
1

XPathExpression expr = xpath.compile("//信息/person[1]/name");

    String str = (String) expr.evaluate(doc, XPathConstants.STRING);

    System.out.println(str);
于 2012-04-12T17:20:39.700 回答