How to parse nested tags in xml files using SAX Parser

958 views Asked by At

I see a bunch of similar threads but haven't quite find one that answers my question. I have an xml like this -

<MyDoc>
  <Book>
    <BookObject>
       <name>Intro to CS</name>
       <year>2009</year>
    <BookObject>
  </Book>
  <CD>
    <CDObject>
       <name>Exercises</name>
       <year>2009</year>
    </CDObject>
    <CDObject>
       <name>Appendix</name>
       <year>2009</year>
    </CDObject>
  </CD>
</MyDoc>

In the startElement I just have this:

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
        tagName = qName;
    }

But I can't figure out how to implement the endElement below

@Override
public void endElement(String uri, String localName, String qName) throws SAXException
{

    if (tagName.equalsIgnoreCase("BookObject"))
    {
        //what here?

    }
}

Looking for links to examples that could be helpful or pointers to the api calls I need to make. I have these POJOS - Book, BookObject, CD, CDObject and MyDoc.

Thanks in advance for any help.

1

There are 1 answers

0
Joseph Larson On

You haven't really told us what you want to do, but what you probably want to do is something like...

In the startElement() -- when you see a beginning, then create a Book object. When you see a , then in your Book object, create a new BookObject. For the things inside the BookObject, you'll need to implement:

public void characters(char[] ch, int start, int length) throws SAXException;

This will get called for the stuff inside your <name> objects, for instance, so you also need to keep track that you're inside one of those.