Java handling XML using SAX

时间秒杀一切 提交于 2019-12-02 10:59:27

问题


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?



来源:https://stackoverflow.com/questions/5844458/java-handling-xml-using-sax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!