我想检查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
}
}
Run Code Online (Sandbox Code Playgroud)
并且我可以添加更多循环以进入子元素,但我必须知道要放入多少嵌套循环来确定要钻取的文档的距离.我可以嵌套10个循环,最后在给定文档中嵌套12个元素的person元素.我需要能够拉出元素而不管嵌套的深度.
有没有办法从整个文档中收集元素?比如将所有标签的文本值作为数组返回或迭代它?
类似于python的elementtree'findall'方法的东西也许:
for person in tree.findall('//person'):
personlist.append(person)
Run Code Online (Sandbox Code Playgroud)
use*_*661 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Kat*_*one 10
我看到三种可能性(其中两种已经回答):
Document(即如果root是
Document),你可以使用
Document.getElementsByTagName