I suggest you read up on what DOM documents look like. In your XML
file, for example, the AUTHOR tag is stored as an ELEMENT_NODE. The
value of this tag (Bob Dylan) will be stored as a TEXT_NODE as a child
of the author node.
So during parsing, if you encounter an author element node, you have
to look at its children to get the value of the author.
A quick naive approach is shown below:
A similar approach could be used for other tags.
//////
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.* ;
// A Simple DOM Application
public class BasicDOM2 {
// Constructor
public BasicDOM2(String xmlFile)
{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(xmlFile) ;
traverse(doc) ;
}
catch (Exception e) {System.out.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() + ": ");
//now get the values which are the children of this node
NodeList children = node.getChildNodes();
if (children != null) {
for (int i=0; i< children.getLength(); i++)
System.out.println(children.item(i).getNodeValue()) ;
}
} 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("test.xml");
}
}
////
Fahd
http://www.fahdshariff.cjb.net
> Hi all,
> I'm having some problems with parsing XML with DOMParser.
[quoted text clipped - 4 lines]
>
> Yang
Yang Xiao - 29 Apr 2004 18:15 GMT
Hi,
Thanks for the pointer, I was confused about the tree like structure
DOM has from the beginning, I saw the TEXT node as an Attribute rather
than a child node of the element. Thanks for clarifying the point,
thanks.
Yang
> I suggest you read up on what DOM documents look like. In your XML
> file, for example, the AUTHOR tag is stored as an ELEMENT_NODE. The
[quoted text clipped - 72 lines]
> >
> > Yang