// JAXP APIs qu'on utilise import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; // les exceptions pouvant etre levees import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; // inputs/outputs import java.io.File; import java.io.IOException; // les definitions W3C pour DOM et les exceptions DOM import org.w3c.dom.*; public class SimpleDomParserCount { private static int elts = 0; private static int attr = 0; private static int proc = 0; private static int text = 0; static final String[] typeName = { "none", "Element", "Attr", "Text", "CDATA", "EntityRef", "Entity", "ProcInstr", "Comment", "Document", "DocType", "DocFragment", "Notation", }; public static void main(String argv[]) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // // si on veut valider le document par rapport a // sa declaration de type // // factory.setValidating(true); // factory.setNamespaceAware(true); // try { DocumentBuilder builder = factory.newDocumentBuilder(); // C'est ici que se fait le parsing Document document = builder.parse(new File(argv[0])); // Parcours et affichage du document walk_the_tree(document); System.out.println("Nbre d'elts : "+elts); System.out.println("Nbre d'attributs : "+attr); System.out.println("Nbre de proc instr : "+proc); System.out.println("Nbre de characteres de texte : "+text); } catch (SAXException sxe) { // Capture des erreurs de parsing Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Capture des erreurs de configuration pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } } ///////////////////////////////////////////////////////////// public static void walk_the_tree(Node domNode) { // Utilisation du tableau defini au debut int type = domNode.getNodeType(); // Traitement du noeud courant // --------------------------- // Cas d'un element if (type == 1) { elts += 1; } // Cas d'un attribut else if (type == 2) { attr +=1; } // Cas de texte else if (type == 3) { if (! "".equals(domNode.getNodeValue().trim())) { text +=domNode.getNodeValue().trim().length(); } } // Cas d'instructions de traitement else if (type == 7) { proc +=1; } else { } // Traitement des attributs du noeud courant //------------------------------------------ NamedNodeMap attrs = domNode.getAttributes(); if (attrs != null) { // un attribut peut contenir des entites .. for (int i = 0; i < attrs.getLength(); i++) walk_the_tree(attrs.item(i)); } // Traitement des noeuds fils du noeud courant //-------------------------------------------- NodeList child = domNode.getChildNodes(); for (int i = 0; i < child.getLength(); i++) walk_the_tree(child.item(i)); } }