XmlPullParser: get inner text including XML tags
Asked Answered
E

1

10

Suppose you have an XML document like so:

<root>
  That was a <b boldness="very">very bold</b> move.
</root>

Suppose the XmlPullParser is on the opening tag for root. Is there a handy method to read all text within root to a String, sort of like innerHtml in DOM?

Or do I have to write a utility method myself that recreates the parsed tag? This of course seems like a waste of time to me.

String myDesiredString = "That was a <b boldness=\"very\">very bold</b> move."
Eward answered 17/4, 2013 at 20:15 Comment(3)
I'm afraid you're bound to write your own function to parse given xml as you wanted to.Hydric
Aw man. :( Maybe I can use SAX parsing though?Eward
Yet I think that you have to reconstruct the bold tag yourself whilst parsing the data. Similarly to pull parser, afaik, SAX parser does handle the bold tag and not give you "inner xml".Hydric
E
12

This method should about cover it, but does not deal with singleton tags or namespaces.

public static String getInnerXml(XmlPullParser parser)
        throws XmlPullParserException, IOException {
    StringBuilder sb = new StringBuilder();
    int depth = 1;
    while (depth != 0) {
        switch (parser.next()) {
        case XmlPullParser.END_TAG:
            depth--;
            if (depth > 0) {
                sb.append("</" + parser.getName() + ">");
            }
            break;
        case XmlPullParser.START_TAG:
            depth++;
            StringBuilder attrs = new StringBuilder();
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                attrs.append(parser.getAttributeName(i) + "=\""
                        + parser.getAttributeValue(i) + "\" ");
            }
            sb.append("<" + parser.getName() + " " + attrs.toString() + ">");
            break;
        default:
            sb.append(parser.getText());
            break;
        }
    }
    String content = sb.toString();
    return content;
}
Eward answered 17/4, 2013 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.