迭代java DOM中的所有XML节点生成
我想检查XML文档是否包含任何内部的'person'元素。我可以检查所有的第一代的元素很简单:迭代java DOM中的所有XML节点生成
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个元素的人物元素。我需要能够拉出元素,不管它的嵌套深度如何。
是否有办法从整个文档中收集元素?像将所有标签的文本值作为数组返回或迭代它一样?
一种近乎蟒蛇的ElementTree '的findall' 的方法也许是:
for person in tree.findall('//person'):
personlist.append(person)
正如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);
}
}
}
这就是XPath的用途。要获取名为“person”的所有元素,请使用以下表达式:
//person
直接使用JDK的XPath API可能很痛苦。我更喜欢我在实际XML库写的包装:http://practicalxml.sourceforge.net/
而这里的,我写的教程(上JDK的XPath一般,但提到XPathWrapper):http://www.kdgregory.com/index.php?page=xml.xpath
我看到三个possiblities(其中两个其他人已经回答):
- 使用递归。
- 使用XPath(这个问题可能有点矫枉过劳 ,但如果你有这样的查询很多 绝对是探索)。 使用kdgregory的帮助;一个 快看api指示 直接使用 有点痛苦。
-
如果你有什么,其实是
Document
(即如果root
是Document
),你可以使用Document.getElementsByTagName
+1 - #3绝对是最简单的方法 – kdgregory 2009-06-23 18:15:35
Document.getElementsByTagName()
或XPath
,你也可以使用jOOX,图书馆我已经创建了更简单的XML访问和操作。 jOOX包装了标准的Java API并增加了类似于效用的方法。然后,您的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);
}
这里是格式化版本:
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");
}
}
}
我想你需要http://en.wikipedia.org/wiki/Recursion_%28computer_science %29。 – 2009-06-23 17:48:38