在Java中,我使用DocumentBuilderFactory、DocumentBuilder和Document来读取xml文件。但是现在我想要创建一个方法,它返回一个数组,其中包含一个给定的节点序列中的所有值。为了更好地解释,我将给出一个示例:假设我有以下xml文件:
<one>
<two>
<three>5</three>
<four>6</four>
</two>
<two>
<three>7</three>
<four>8</four>
</two>
</one>我使用带有字符串参数"one.two.three“的方法,现在返回值应该是包含数字5和7的数组。
我怎样才能建立这个列表呢?
发布于 2014-06-05 17:57:03
您可以使用xpath,尽管语法与点略有不同(使用斜杠)
Document d = ....
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/one/two/three/text()"); // your example expression
NodeList nl = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
String n = nl.item(i).getTextContent();
System.out.println(n); //now do something with the text, like add them to a list or process them directly
}您可以找到关于如何使用xpath 这里查询节点的更多信息。
https://stackoverflow.com/questions/24066690
复制相似问题