package xml.musicCatalog;
import java.io.*;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.DOMException;
import org.w3c.dom.ranges.DocumentRange;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class MyDomParser {
private static DOMParser parser = null;
private static PrintStream out = null;
static final int ELEMENT_NODE = 1;
static final int ATTR_NODE = 2;
static final int TEXT_NODE = 3;
public static void parse (String uri, OutputStream os)
throws Exception {
try {
out = new PrintStream(os);
parser = new DOMParser();
parser.parse(uri);
Document domDocument = parser.getDocument();
Element root = domDocument.getDocumentElement();
traverse(root);
out.flush();
}
catch (SAXException e) {
out.flush();
Exception ex = e.getException();
String msg = null;
if (ex != null) {
ex.printStackTrace();
msg = ex.getMessage();
}
throw new Exception(
"** SAXException:\n" + e.getMessage());
}
catch (IOException e) {
out.flush();
throw new Exception(
"IOException:\n" + e.getMessage());
}
}
public static void traverse (Node elem) {
try {
if (elem.hasAttributes()) {
NamedNodeMap attrs = elem.getAttributes();
int alength = attrs.getLength();
for (int i=0; i<alength; i++) {
Attr attr = (Attr) attrs.item(i);
out.println(attr.getName() + ":\t" + attr.getValue());
}
}
if (elem.hasChildNodes()) {
NodeList children = elem.getChildNodes();
int length = children.getLength();
for (int i=0; i<length; i++) {
Node n = children.item(i);
String name = n.getNodeName();
if (n.getNodeType() == ELEMENT_NODE) {
if (name.equals("Item"))
out.println("\n");
else
out.print(name + ":\t");
traverse(n); }
else
if (n.getNodeType() == TEXT_NODE) {
String txt = n.getNodeValue().trim();
if (! txt.equals("")) {
out.println(txt);
}
}
}
return;
}
}
catch (DOMException e) {
System.out.println(
"*** DOMException\n" + e.getMessage());
}
}
}