栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java:最有效的方法来遍历org.w3c.dom.Document中的所有元素?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java:最有效的方法来遍历org.w3c.dom.Document中的所有元素?

基本上,您可以通过两种方式遍历所有元素:

1.使用递归 (我认为是最常见的方式):

public static void main(String[] args) throws SAXException, IOException,        ParserConfigurationException, TransformerException {    documentBuilderFactory docBuilderFactory = documentBuilderFactory        .newInstance();    documentBuilder docBuilder = docBuilderFactory.newdocumentBuilder();    document document = docBuilder.parse(new File("document.xml"));    doSomething(document.getdocumentElement());}public static void doSomething(Node node) {    // do something with the current node instead of System.out    System.out.println(node.getNodeName());    NodeList nodeList = node.getChildNodes();    for (int i = 0; i < nodeList.getLength(); i++) {        Node currentNode = nodeList.item(i);        if (currentNode.getNodeType() == Node.ELEMENT_NODE) { //calls this method for all the children which is Element doSomething(currentNode);        }    }}

2. 使用

getElementsByTagName()
带有
*
as参数的方法 避免递归

public static void main(String[] args) throws SAXException, IOException,        ParserConfigurationException, TransformerException {    documentBuilderFactory docBuilderFactory = documentBuilderFactory .newInstance();    documentBuilder docBuilder = docBuilderFactory.newdocumentBuilder();    document document = docBuilder.parse(new File("document.xml"));    NodeList nodeList = document.getElementsByTagName("*");    for (int i = 0; i < nodeList.getLength(); i++) {        Node node = nodeList.item(i);        if (node.getNodeType() == Node.ELEMENT_NODE) { // do something with the current element System.out.println(node.getNodeName());        }    }}

我认为这些方式都很有效。
希望这可以帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569321.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号