博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jaxp与dom4j遍历xml树
阅读量:5157 次
发布时间:2019-06-13

本文共 3662 字,大约阅读时间需要 12 分钟。

1、jaxp遍历xml树

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
public class Main {
  public static void main(String[] argvthrows Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.parse("sample.xml");
    DocumentTraversal traversal = (DocumentTraversaldocument;
    NodeIterator iterator = traversal.createNodeIterator(document.getDocumentElement(),
        NodeFilter.SHOW_ELEMENT, null, true);
    for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
      System.out.println("Element: " ((Elementn).getTagName());
    }
  }
}

2、dom4j遍历xml树

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

public void bar(Document document) throws DocumentException {        Element root = document.getRootElement();        // iterate through child elements of root        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {            Element element = (Element) i.next();            // do something        }        // iterate through child elements of root with element name "foo"        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {            Element foo = (Element) i.next();            // do something        }        // iterate through attributes of root         for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {            Attribute attribute = (Attribute) i.next();            // do something        }     }
 

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

public void treeWalk(Document document) {        treeWalk( document.getRootElement() );    }    public void treeWalk(Element element) {        for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {            Node node = element.node(i);            if ( node instanceof Element ) {                treeWalk( (Element) node );            }            else {                // do something....            }        }    }
 

Using Visitor Pattern

The visitor pattern has a recursive behavior and acts like SAX in the way that partial traversal is not possible. This means complete document or complete branch will be visited. You should carefully consider situations when you want to use Visitor pattern, but then it offers a powerful and elegant way of navigation. This document doesn't explain Vistor Pattern in depth, GoF98 covers more information.

import java.util.Iterator;import org.dom4j.Visitor;import org.dom4j.VisitorSupport;import org.dom4j.Document;import org.dom4j.Element;public class VisitorSample {  public void demo(Document doc) {    Visitor visitor = new VisitorSupport() {      public void visit(Element element) {        System.out.println(          "Entity name: " + element.getName()  + "text " + element.getText();        );      }    };    doc.accept( visitor );  }}

As you can see we used anonymous inner class to override the VisitorSupport callback adapter method visit(Element element) and the accept() method starts the visitor mechanism.

Accessing XML content statically alone would not very special. Thus dom4j offers several methods for manipulation a documents content.

转载于:https://www.cnblogs.com/snowberg/archive/2011/09/13/2468602.html

你可能感兴趣的文章
5G边缘网络虚拟化的利器:vCPE和SD-WAN
查看>>
MATLAB基础入门笔记
查看>>
【UVA】434-Matty&#39;s Blocks
查看>>
Android开发技术周报 Issue#80
查看>>
hadoop2.2.0+hive-0.10.0完全分布式安装方法
查看>>
django知识点总结
查看>>
C++ STL stack、queue和vector的使用
查看>>
使用Reporting Services时遇到的小问题
查看>>
约瑟夫问题
查看>>
Arduino 报错总结
查看>>
树莓派Android Things物联网开发:树莓派GPIO引脚图
查看>>
矩阵快速幂---BestCoder Round#8 1002
查看>>
js兼容公用方法
查看>>
如何将应用完美迁移至Android P版本
查看>>
【转】清空mysql一个库中的所有表的数据
查看>>
基于wxPython的python代码统计工具
查看>>
淘宝JAVA中间件Diamond详解(一)---简介&快速使用
查看>>
Hadoop HBase概念学习系列之HBase里的宽表设计概念(表设计)(二十七)
查看>>
Kettle学习系列之Kettle能做什么?(三)
查看>>
Day03:Selenium,BeautifulSoup4
查看>>