【发布时间】:2019-10-02 11:15:14
【问题描述】:
我有以下 xml:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.test.com/rest/v1" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<child test="folder" id="2019-05-15-04.52.05.641880A01" />
<child test="folder" id="2019-05-15-04.52.05.901880A02" />
</root>
我想通过使用 Java 代码和 Xpath 读取上面的 xml,检索子节点的 id(即id="2019-05-15-04.52.05.641880A01" and id="2019-05-15-04.52.05.901880A02")并将它们存储到 List 中。我尝试使用以下 java 代码:
InputSource source = new InputSource(new StringReader(xml));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document document = db.parse(source);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
return xpath.evaluate(expression, document);
我用下面的 Xpath 和输入的 xml 调用了上面的方法:
*[local-name()='root']/*[local-name()='child']/@id
但我只得到一个 id,而不是所有的 id。关于如何获取所有 id 的任何想法?
【问题讨论】:
-
Java 的内置 DOM 和 XPath 库很糟糕。你需要做
xpath.evaluate(expression, document, XPathConstants.NODESET) -
@kumesana,能否请您告诉我上述 xml 的确切表达方式,以便我处理扩孔的事情?