Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java XML: Parcourir un arbre DOM en utilisant la classe TreeWalker

Java XML: Parcourir un arbre DOM en utilisant la classe TreeWalker
{filelink=8544}

/***** Code de MesExemples.com *******/
/**
 * @(#)XMLIterateDOMWithTreeWalker.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/7/5
 */
 
 
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.TreeWalker;
 
public class XMLIterateDOMWithTreeWalker {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.parse("test2.xml");
 
    DocumentTraversal traversal = (DocumentTraversal) document;
 
    TreeWalker walker = 
    traversal.createTreeWalker(document.getDocumentElement(),
        NodeFilter.SHOW_ELEMENT, null, true);
 
    recursiveTraverse(walker, "");
  }
 
  private static final void recursiveTraverse(TreeWalker walker, String 
    indent) {
    Node parend = walker.getCurrentNode();
    System.out.println(indent + "- " + ((Element) parend).getTagName());
 
    for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
      recursiveTraverse(walker, indent + ' ');
    }
    walker.setCurrentNode(parend);
  }
}

Code testé avec le fichier XML Suivant

<?xml version="1.0" encoding="windows-1252"?>
<!-- Edited by MesEXemple.com -->
<note>
	<to>Sakoba</to>
	<from>Adams</from>
	<heading>Rappel</heading>
	<body>Ne m'oubliez pas ce week-end!</body>
</note>