Java-readxml文件
在Java中,我使用DocumentBuilderFactory、DocumentBuilder和Document来读取xml文件。 但是现在我想创建一个方法,它返回一个arraylist,其中包含给定节点序列后面的所有值。为了更好地解释,我将举一个例子: 假设我有以下xml文件:Java-readxml文件,java,xml,Java,Xml,在Java中,我使用DocumentBuilderFactory、DocumentBuilder和Document来读取xml文件。 但是现在我想创建一个方法,它返回一个arraylist,其中包含给定节点序列后面的所有值。为了更好地解释,我将举一个例子: 假设我有以下xml文件: <one> <two> <three>5</three> <four>6</four> </two> &
<one>
<two>
<three>5</three>
<four>6</four>
</two>
<two>
<three>7</three>
<four>8</four>
</two>
</one>
5.
6.
7.
8.
我使用带有字符串参数“one.two.three”的方法,现在返回值应该是一个包含数字5和7的数组
如何构建此arraylist?您可以使用xpath,尽管语法与点略有不同(使用斜杠)
文档d=。。。。
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“/one/two/three/text()”);//您的示例表达式
NodeList nl=(NodeList)expr.evaluate(d,XPathConstants.NODESET);
对于(int i=0;i
您可以找到有关如何使用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
}