jaxp与dom4j遍历xml树

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.





你可能感兴趣的:(dom4j)