Hi all,
I'm having some problems with parsing XML with JDOM.
What I want is to filter out particular elements in the XML,
the sample XML looks like this.
Thanks in advance.
Yang
<CATALOG>
<CD>
<TITLE>Empire
Burlesque</TITLE>
<ARTIST>Bob
Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide
your heart</TITLE>
<ARTIST>Bonnie
Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS
Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Greatest
Hits</TITLE>
<ARTIST>Dolly
Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
</CATALOG>
and my code(which doesn't work J)
import java.io.IOException;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
// A Simple DOM Application
public class BasicDOM2 {
// Constructor
public BasicDOM2(String xmlFile) {
// Create a Xerces DOM Parser
DOMParser parser = new DOMParser();
// Parse the Document
// and traverse the DOM
try {
parser.parse(xmlFile);
Document document = parser.getDocument();
traverse(document);
} catch (SAXException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
// Traverse DOM Tree. Print out Element Names
private void traverse(Node node) {
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE && node.getNodeName().equals("ARTIST")){
System.out.print(node.getNodeName() + ": ");
System.out.print(node.getNodeValue());
process(node);
} else {
}
/*
if (type == Node.TEXT_NODE){// && node.getNodeName().equals("ARTIST"))
System.out.println(node.getNodeValue());
// System.out.println(node.getLocalName());
}else{
}
*/
NodeList children = node.getChildNodes();
if (children != null) {
for (int i=0; i< children.getLength(); i++)
traverse(children.item(i));
}
}
// Main Method
public static void main(String[] args) {
BasicDOM2 basicDOM = new BasicDOM2("c:/temp/cd2.xml");
}
public void process(Node node){
StringBuffer buf = new StringBuffer();
Node n = node;
//NodeList nl = textNode.getChildNodes();
//for( int i=0; i<nl.getLength(); i++ ){
// n = nl.item(i);
if( n.getNodeType() == Node.TEXT_NODE ) {
buf.append( n.getNodeValue() );
}else{
// expected a text-only node!
}
//}
System.out.println(buf.toString());
}
}