【发布时间】: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)
【问题讨论】: