Java handling XML using SAX

前端 未结 1 1209
日久生厌
日久生厌 2021-01-23 12:29

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

 

  
    

        
相关标签:
1条回答
  • 2021-01-23 13:05

    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?

    0 讨论(0)
提交回复
热议问题