简体   繁体   中英

How to parse nested tags in xml files using SAX Parser

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM