gpt4 book ai didi

java - 在java中无需迭代即可获取节点的xpath值

转载 作者:行者123 更新时间:2023-12-02 07:52:08 26 4
gpt4 key购买 nike

我有一个 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);

最佳答案

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

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

System.out.println(str);

关于java - 在java中无需迭代即可获取节点的xpath值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10111360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com