Search code examples
androidsaxsaxparser

How to parse node that has TEXT or Child nodes in Android SAX


I am trying to parse the below XML using SAX:

<feed>
<item>
    <link>
        <type>MY TYPE</type>
        <id>123456789</id>
        <key>123456789</key>
    </link>
</item>
<item>
    <link>htt://www.example.com</link>
</item>
</feed>

The node link can have either child nodes (type, id, key) or text.

I tried using the below code snippet:

RootElement root = new RootElement("feed");
Element item = root.getChild("item");

item.getChild("link").setEndTextElementListener(new EndTextElementListener() {
  public void end(String body) {
    // Grab link text
  }
});

item.getChild("link").getChild("type").setEndTextElementListener(new EndTextElementListener() {
  public void end(String body) {
    // Get type node text
  }
});

But the problem is that SAX throws the below Exception:

if (endTextElementListener != null) {
throw new IllegalStateException("This element already has an end"
        + " text element listener. It cannot have children.");
}

Is there any way around parsing nodes that can have TEXT or child nodes? OR does the XML structure need to change?


Solution

  • Apparently this is not possible using the default handler, so I ended up implementing a custom handler to work around this issue.