Java handling XML using SAX

2019-02-27 22:20发布

问题:

I've got XML I need to parse with the given structure:

<?xml version="1.0" encoding="UTF-8"?> 
<root>
  <tag label="idAd">
    <child label="text">Text</child>
  </tag>
  <tag label="idNumPage">
    <child label1="text" label2="text">Text</child>
  </tag>
</root>

I use SAX parser to parse it:

RootElement root=new RootElement("root");
android.sax.Element page_info=root.getChild("tag").getChild("child");
page_info.setStartElementListener(new StartElementListener() {

            @Override
            public void start(Attributes attributes) {
                /*---------------*/
            }
        });

I want to read second "tag" element attributes(label1 and label2), but my StartElementListener reads first tag, because they have the same structure and attributes(those label="idAd" and label="idNumPage") distinguish them. How do I tell StartElementListener to process only second <tag> element?

回答1:

If you are stuck with the StartElementListener-way, you should set a listener to the tag element, and when it's label equals "idNumPage" set a flag, so the other StartElementListener you've set on the child element should be read.

Update
Below is a sample of how to do this using these listeners:

android.sax.Element tag = root.getChild("tag");
final StartTagElementListener listener = new StartTagElementListener();
tag.setStartElementListener(listener);

android.sax.Element page_info = tag.getChild("child");
page_info.setStartElementListener(new StartElementListener()
{
    @Override
    public void start(Attributes attributes)
    {
        if (listener.readNow())
        {
            //TODO: you are in the tag with label="idNumPage"
        }
    }
});

And the StartTagElementListener is implemented with an extra readNow getter, to let us know when to read the child tag's attributes:

public final class StartTagElementListener implements StartElementListener
{
    private boolean doReadNow = false;

    @Override
    public void start(Attributes attributes)
    {
        doReadNow = attributes.getValue("label").equals("idNumPage");
    }

    public boolean readNow()
    {
        return doReadNow;
    }
}

PS: Did you consider using a org.xml.sax.helpers.DefaultHandler implementation for this task?