2013-04-17 18 views
8

Supponiamo di avere un documento XML in questo modo:XmlPullParser: ottenere testo interno compresi i tag XML

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

Supponiamo che il XmlPullParser è sul tag di apertura per root. C'è un metodo pratico per leggere tutto il testo all'interno di root su un String, una specie di come innerHtml in DOM?

Oppure devo scrivere personalmente un metodo di utilità che ricrea il tag analizzato? Questo ovviamente mi sembra una perdita di tempo.

String myDesiredString = "That was a <b boldness=\"very\">very bold</b> move." 
+1

Ho paura che tu sia obbligato a scrivere la tua funzione per analizzare xml dato come volevi. – harism

+0

Aw man. :(Forse posso usare l'analisi SAX però? – Maarten

+0

Eppure penso che tu debba ricostruire il tag grassetto mentre stai analizzando i dati. Analogamente al parser, afaik, il parser SAX gestisce il tag grassetto e non ti dà "inner xml" . – harism

risposta

10

Questo metodo dovrebbe coprirlo, ma non trattare tag o spazi dei nomi Singleton.

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; 
}