Java 如何仅获取 ELEMENT_NODE 类型的子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20089661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get child nodes with ELEMENT_NODE type only
提问by chuonghd
I'm parsing a xml document using java DOM and I need to get every single node for doing something.
我正在使用 java DOM 解析 xml 文档,我需要获取每个节点来做某事。
I have this code:
我有这个代码:
public void analyze_file(Node node){
if(node.getNodeType() != Node.DOCUMENT_NODE){
//do something
}
NodeList list = node.getChildNodes();
for(int i=0; i<list.getLength(); i++){
if(list.item(i).getNodeType() == Node.ELEMENT_NODE){
analyze_file(list.item(i));
}
}
}
The problem is that, my xml file is very large ( > 30000 lines), and the code above needs too much time for checking whether a node is of ELEMENT_NODE
type or not. I see that if the program stopped after it reached the last ELEMENT_NODE
node, the execution time would be very small.
问题是,我的xml文件非常大(> 30000行),上面的代码需要太多时间来检查节点是否为ELEMENT_NODE
类型。我看到如果程序在到达最后一个ELEMENT_NODE
节点后停止,则执行时间将非常小。
Is there any way to get all child nodes whose type is ELEMENT_NODE
only?
有没有办法获取所有类型为ELEMENT_NODE
only 的子节点?
For example: NodeList list = node.getElementChildNodes();
例如: NodeList list = node.getElementChildNodes();
Thanks for any help!
谢谢你的帮助!
采纳答案by pasha701
node.getElementsByTagName("*")
From JavaDoc: Returns a NodeList of all descendant Elements with a given tag name, in document order. Name - The name of the tag to match on. The special value "*" matches all tags.
来自 JavaDoc:以文档顺序返回具有给定标记名称的所有后代元素的 NodeList。名称 - 要匹配的标签的名称。特殊值“*”匹配所有标签。