// File: xmltest2.java // // Author: Rahul Simha // Version: Feb 11, 2000 // // Second example in XML tutorial import com.ibm.xml.parser.*; import org.w3c.dom.*; import java.io.*; // An error-handling class passed to the parser that // overrides the error method. class MyErrorHandler implements ErrorListener { public int error (String fname, int lineno, int charoff, Object key, String mes) { System.out.println ("ERR:" + fname + " at line " + lineno + ": " + mes); return 1; } } public class xmltest2 { // The method clean removes all nodes with "junk" data. public static void clean (Node n) { boolean remove = false; // Extract the nodename. String nodename = n.getNodeName(); if (nodename != null) { // Removing is a possibility only if the node is of type "#text". if (nodename.equals ("#text")) remove = true; else remove = false; } // Extract the node value. String valueStr = n.getNodeValue(); int len = 0; // Now trim and check if it needs to be removed. if (valueStr != null) { valueStr = valueStr.trim(); len = valueStr.length(); if (len > 0) { // Useful remove = false; // Put the trimmed string back in. n.setNodeValue (valueStr); } } if (remove) { // To remove, go to the parent node and delete from there. Node p = n.getParentNode(); p.removeChild (n); // Recursively clean. clean (p); return; } // Continue exploration. if (n.hasChildNodes()) { NodeList nl = n.getChildNodes(); int size = nl.getLength(); for (int i=0; i 0) { try { FileReader fr = new FileReader (argv[0]); // Pass errorhandler to parser. Parser p = new Parser (argv[0], new MyErrorHandler(), null); // The next few steps are straightforward: p.setKeepComment (false); p.setPreserveSpace (false); TXDocument doc = p.readStream(fr); Element root = doc.getDocumentElement (); // Always a good check: if (root == null) return; // First clean: System.out.println ("CLEAN ..."); clean (root); // Then, traverse: System.out.println ("TRAVERSE ..."); traverse (root); // Add a new "student" to the tree. System.out.println ("ADDING A NEW STUDENT: "); NodeList nl = doc.getElementsByTagName ("STUDENT"); Node n = nl.item(1); Node s = makeStudent (n, "Dangerous Dave", "333 Ouch St", "C"); Node parent = n.getParentNode(); // Note the use of appendChild(): parent.appendChild (s); // OK, traverse again to see what we've done. System.out.println ("TRAVERSE ..."); traverse (root); } catch (IOException e) { System.out.println ("Usage: java xmltest2 "); } } else { System.out.println ("Usage: java xmltest2 "); } } }