parsing XML with DOMParser

Y

Yang Xiao

Hi all,
I'm having some problems with parsing XML with DOMParser.
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());
} 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");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top