迭代java DOM中的所有XML节点生成

时间:2009-06-23 17:45:41

标签: java xml dom

我想检查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)

5 个答案:

答案 0 :(得分:10)

正如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);
        }
    }
}

答案 1 :(得分:10)

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

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

答案 2 :(得分:4)

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

//person

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

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

答案 3 :(得分:2)

以下是格式化版本:

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");
      }
    }
}

答案 4 :(得分:0)

除了Document.getElementsByTagName()XPath之外,您还可以使用jOOX,这是我为更简单的XML访问和操作而创建的库。 jOOX包含标准Java API并添加jquery - 就像实用程序方法一样。然后,您的Python代码段将转换为此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);
}