Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java XML DOM: Afficher les nœuds d’un arbre DOM

Java XML DOM: Afficher les nœuds d'un arbre DOM
{filelink=8557}

/***** Code de MesExemples.com *******/
/**
 * @(#)DOMShowNode.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/7/5
 */
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
public class DOMShowNode {
 
public static void main (String[] args)throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();
    Document doc = loader.parse("test2.xml");
    Element element = doc.getDocumentElement();
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) 
    	{
      Node child = children.item(i);
      printTree(child);
       }
}
  public static void printTree(Node doc) {
    if (doc == null) {
      System.out.println("Nothing to print!!");
      return;
    }
    try {
      System.out.println(doc.getNodeName() + "  " + doc.getNodeValue());
      NamedNodeMap cl = doc.getAttributes();
      for (int i = 0; i < cl.getLength(); i++) {
        Node node = cl.item(i);
        System.out.println(
          " " + node.getNodeName() + " ->" + node.getNodeValue());
      }
      NodeList nl = doc.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        printTree(node);
      }
    } catch (Throwable e) {
      System.out.println("Cannot print!! " + e.getMessage());
    }
  }
 
}

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>