[英]Java XML - nested elements with same name
How can I reach to elements which have same name and recursive inclusion using Java XML? 如何使用Java XML到达具有相同名称和递归包含的元素? This has worked in python ElementTree, but for some reason I need to get this running in Java.
这已经在python ElementTree中工作了,但是由于某种原因,我需要让它在Java中运行。
I have tried: 我努力了:
String filepath = ("file.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
NodeList nl = doc.getElementsByTagName("*/*/foo");
Example 例
<foo>
<foo>
<foo>
</foo>
</foo>
</foo>
You seem to be under the impression that getElementsByTagName
takes an XPath expression. 似乎给人的印象是
getElementsByTagName
采用XPath表达式。 It doesn't. 没有。 As documented:
根据记录:
Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.
返回具有给定标签名称并按文档顺序包含在文档中的所有Elements的NodeList。
If you need to use XPath, you should look at the javax.xml.xpath
package. 如果需要使用XPath,则应查看
javax.xml.xpath
包。 Sample code: 样例代码:
Object set = xpath.evaluate("*/*/foo", doc, XPathConstants.NODESET);
NodeList list = (NodeList) set;
int count = list.getLength();
for (int i = 0; i < count; i++) {
Node node = list.item(i);
// Handle the node
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.