简体   繁体   中英

SAX Parser ignoring parent elements? Same named elements grouped as a result

I'm not if this is just how SAX Parser is supposed to work or if I am missing something.

This is the sort of XML I am pulling down from my server:

<Data>
    <Item id="1">
        <Group>
          <Name>Question One</Name>
          <type>true</type>

          <Selection>
              <Name>Answer 1</Name>
          </Selection>
        </Group>
    </Item>
    <Item id="2">
        <Group>
          <Name>Question Two</Name>
          <type>true</type>

          <Selection>
              <Name>Answer 2</Name>
          </Selection>
        </Group>
    </Item>
</Data>

As you can see, there is an element called "Name" that is showing up twice under different parents, containing different data. I am trying to collect "Question One" and "Question Two" in an ArrayList where I have a getter and setter of setName getName. As the title suggest my result means even the Answers are being collected into the ArrayList for that type.

Is there a way to only pull "Name" that refers to Question One and Question Two? Here is how I have it now in my end element:

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

    if (qName.equalsIgnoreCase("name")) {
        dataItem.setName(currentValue);
    }

Obviously I'm only looking for name, but when I've tried it for "group" then put a second if state inside I have not had any luck either. It's essentially ignoring the parents, group and selection and just collecting everything called name. Using localName also does not help.

I would really appreciate your help, thanks in advance.

SAX pays no attention to the hierarchy, but you can compensate for it in your code.

The startElement , characters and endElement methods are called appropriately on each start tag, character content and end tag in the order that they appear, so what you want to do is recognize the <Selection> tag in your startElement and set a flag in your handler to remember to ignore any <name> tags that occur until you unset the flag on hitting the </Selection> tag and recognizing it in your endElement method.

If you post a bit more of your ContentHandler code, I could probably suggest specific changes.

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