// File: xmltest3.java // // Author: Rahul Simha // Version: Feb 11, 2000 // // Demonstrates node addition and writing XML output. import com.ibm.xml.parser.*; import org.w3c.dom.*; import java.io.*; import java.util.*; // 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 xmltest3 { // The method clean removes all nodes with "junk" data. public static void clean (Node n) { boolean remove = false; 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"); // Continue printing recursively. if (n.hasChildNodes()) { NodeList nl = n.getChildNodes(); int size = nl.getLength(); for (int i=0; i"); } } public static void main (String[] argv) { if (argv.length > 0) { try { FileReader fr = new FileReader (argv[0]); Parser p = new Parser (argv[0]); p.setKeepComment (false); p.setPreserveSpace (false); TXDocument doc = p.readStream(fr); Element root = doc.getDocumentElement (); clean (root); System.out.println ("TRAVERSE ..."); traverse (root); 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(); parent.appendChild (s); System.out.println ("TRAVERSE ..."); traverse (root); // Next, output using the document's print method. FileWriter fw = new FileWriter ("studentout.xml"); PrintWriter pw = new PrintWriter (fw); doc.print (pw); pw.close(); // Our own custom writing approach. // NOTE: this does not print the DTD, for unknown reasons. String charset = "ISO-8859-1"; String jencode = MIME2Java.convert (charset); fw = new FileWriter ("studentout2.xml"); pw_out = new PrintWriter (fw); DTD dtd = doc.getDTD(); dtd.toXMLString (pw_out); pw_out.flush(); pw_out.close(); } catch (IOException e) { System.out.println ("Usage: java xmltest3 "); } } else { System.out.println ("Usage: java xmltest3 "); } } }