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
}

更多相关文章

  1. 二分法查找递归方式()
  2. Java递归实现算24

随机推荐

  1. 几种常见的android Runtime异常
  2. Android中使用ALSA声卡
  3. Android 测试工具集02
  4. Android之拨号器
  5. Android 深入解析用户界面(四)
  6. android中log知识总结
  7. android notes(1)
  8. android 自定义组件圆形边框
  9. Ubuntu 将adb加入环境变量
  10. Android控件常用属性