// File: xmltest.java // // Author: Rahul Simha // Version: Feb 11, 2000 // // A simple demonstration of XML parsing. import com.ibm.xml.parser.*; import org.w3c.dom.*; import java.io.*; public class xmltest { // Traverse a subtree whose root is the parameter. public static void traverse (Node n) { // Extract node info: String nodename = n.getNodeName(); String valueStr = n.getNodeValue(); // Print and continue traversing. System.out.println ("Node: " + n.getNodeName() + " value=[" + valueStr + "]"); // Now traverse the rest of the tree in depth-first order. if (n.hasChildNodes()) { // Get the children in a list. NodeList nl = n.getChildNodes(); // How many of them? int size = nl.getLength(); for (int i=0; i 0) { try { // Get the XML file name, e.g., "student.xml". FileReader fr = new FileReader (argv[0]); // Create a parser instance. Parser p = new Parser (argv[0]); // These two will decide whether the parser will // retain whitespace and comments from the original file. p.setKeepComment (false); p.setPreserveSpace (false); // Now parse and create a document tree as a result. // Note that we are passing a FileReader wrapped around // the file. TXDocument doc = p.readStream(fr); // Once we have the tree, extract the root. Element root = doc.getDocumentElement (); // Now traverse the tree. System.out.println ("TRAVERSE ..."); traverse (root); // Alternatively, here is a scan by TAG name // for the tag "NAME". System.out.println ("BY THE TAG 'NAME': "); NodeList nl = doc.getElementsByTagName ("NAME"); int size = nl.getLength(); for (int i=0; i"); } } else { System.out.println ("Usage: java xmltest "); } } }