parsing XML with DOMParser

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Yang Xiao

    #1

    parsing XML with DOMParser

    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>Columb ia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
    </CD>
    <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonni e Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
    </CD>
    <CD>
    <TITLE>Greate st 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.IOExcep tion;
    import org.apache.xerc es.parsers.DOMP arser;
    import org.w3c.dom.Doc ument;
    import org.w3c.dom.Nod e;
    import org.w3c.dom.Nod eList;
    import org.xml.sax.SAX Exception;


    // A Simple DOM Application
    public class BasicDOM2 {

    // Constructor
    public BasicDOM2(Strin g xmlFile) {

    // Create a Xerces DOM Parser
    DOMParser parser = new DOMParser();

    // Parse the Document
    // and traverse the DOM
    try {
    parser.parse(xm lFile);
    Document document = parser.getDocum ent();
    traverse(docume nt);
    } catch (SAXException e) {
    System.err.prin tln(e);
    } catch (IOException e) {
    System.err.prin tln(e);
    }
    }

    // Traverse DOM Tree. Print out Element Names
    private void traverse(Node node) {

    int type = node.getNodeTyp e();
    if (type == Node.ELEMENT_NO DE &&
    node.getNodeNam e().equals("ART IST")){
    System.out.prin t(node.getNodeN ame() + ": ");
    System.out.prin t(node.getNodeV alue());
    } else {
    }

    /*
    if (type == Node.TEXT_NODE) {// &&
    node.getNodeNam e().equals("ART IST"))
    System.out.prin tln(node.getNod eValue());
    // System.out.prin tln(node.getLoc alName());
    }else{
    }
    */

    NodeList children = node.getChildNo des();
    if (children != null) {
    for (int i=0; i< children.getLen gth(); i++)
    traverse(childr en.item(i));
    }

    }

    // Main Method
    public static void main(String[] args) {
    BasicDOM2 basicDOM = new BasicDOM2("c:/temp/cd2.xml");
    }
    }
Working...