Java XML - 具有相同名称的嵌套元素
16lz
2021-01-22
How can I reach to elements which have same name and recursive inclusion using Java XML? This has worked in python ElementTree, but for some reason I need to get this running in Java.
如何使用Java XML访问具有相同名称和递归包含的元素?这在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>
1 个解决方案
#1
2
You seem to be under the impression that getElementsByTagName
takes an XPath expression. It doesn't. As documented:
您似乎认为getElementsByTagName采用XPath表达式。它没有。记录如下:
Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.
以文档顺序返回具有给定标记名称的所有元素的NodeList,并包含在文档中。
If you need to use XPath, you should look at the javax.xml.xpath
package. Sample code:
如果需要使用XPath,则应查看javax.xml.xpath包。示例代码:
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
}