【问题标题】:Iterate all XML node generations in java DOM迭代java DOM中的所有XML节点生成
【发布时间】:2010-11-05 06:22:04
【问题描述】:

我想检查一个 XML 文档中是否包含“person”元素。我可以非常简单地检查所有第一代元素:

NodeList nodeList = root.getChildNodes();
for(int i=0; i<nodeList.getLength(); i++){
  Node childNode = nodeList.item(i);
  if (childNode.getNodeName() == "person") {
     //do something with it
  }
}

而且我可以添加更多循环进入子元素,但我必须知道要放入多少嵌套循环才能确定要在文档中钻多远。我可以嵌套 10 个循环,最终在给定文档中嵌套 12 个元素的 person 元素。我需要能够拉出元素,无论它嵌套多深。

有没有办法从整个文档中获取元素?喜欢将所有标签的文本值作为数组返回或对其进行迭代?

可能类似于 python 的 elementtree 'findall' 方法:

for person in tree.findall('//person'):
   personlist.append(person)

【问题讨论】:

标签: java xml dom


【解决方案1】:

正如 mmyers 所说,您可以对这个问题使用递归。

doSomethingWithAll(root.getChildNodes());

void doSomethingWithAll(NodeList nodeList)
{
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);
        if (childNode.getNodeName().equals("person")) {
            //do something with it
        }

        NodeList children = childNode.getChildNodes();
        if (children != null)
        {
            doSomethingWithAll(children);
        }
    }
}

【讨论】:

    【解决方案2】:

    我看到了三种可能性(其他人已经回答了其中两种):

    1. 使用递归。
    2. 使用 XPath(可能有点矫枉过正 对于这个问题,但如果你有 很多这样的查询 绝对值得探索)。 使用 kdgregory 的帮助;一种 快速查看 api 表明 使用起来有点痛苦 直接。
    3. 如果您所拥有的实际上是 Document(也就是说,如果 rootDocument),你可以使用 Document.getElementsByTagName

    【讨论】:

      【解决方案3】:

      这就是 XPath 的用途。要获取所有名为“person”的元素,表达式如下:

      //person
      

      直接使用 JDK 的 XPath API 会很痛苦。我更喜欢我在 Practical XML 库中编写的包装器:http://practicalxml.sourceforge.net/

      这是我写的教程(一般是关于 JDK XPath,但提到了 XPathWrapper):http://www.kdgregory.com/index.php?page=xml.xpath

      【讨论】:

        【解决方案4】:

        这是格式化的版本:

        Element root = xmlData.getDocumentElement();  
        NodeList children = root.getChildNodes(); 
        
        public void doSomethingWithAllToConsole(NodeList nodeList, String tabs)
        {
            for(int i=0; i<nodeList.getLength(); i++){
        
              //print current node & values
              Node childNode = nodeList.item(i);
              if(childNode.getNodeType()==Node.ELEMENT_NODE){
                  System.out.print(tabs + childNode.getNodeName());
                  if(childNode.getFirstChild()!=null 
                          && childNode.getFirstChild().getNodeType()==Node.TEXT_NODE
                          && !StringUtil.isNullOrEmpty(childNode.getFirstChild().getNodeValue()) ){
                      System.out.print(" = " + childNode.getFirstChild().getNodeValue());
                  }
                  System.out.println();
              }
        
              //recursively iterate through child nodes
              NodeList children = childNode.getChildNodes();
              if (children != null)
              {
                  doSomethingWithAllToConsole(children, tabs+"\t");
              }
            }
        }
        

        【讨论】:

          【解决方案5】:

          除了Document.getElementsByTagName()XPath,您还可以使用jOOX,这是我为更简单的XML 访问和操作而创建的一个库。 jOOX 包装了标准 Java API 并添加了类似 jquery 的实用方法。然后,您的 Python 代码 sn-p 将转换为以下 Java 代码:

          // Just looking for tag names
          for (Element person : $(tree).find("person")) {
            personlist.append(person);
          }
          
          // Use XPath for more elaborate queries
          for (Element person : $(tree).xpath("//person")) {
            personlist.append(person);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-09-18
            相关资源
            最近更新 更多