2014-04-24 41 views
0

所有文字形式的特定標記可以說我有一個包含如何提取XML的Android上

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <element> 
    <item> 
     <p>text 1</p> 
     <p>text 2</p> 
    </item> 
    <item> 
     <p>text 3</p> 
     <p>text 4</p> 
    </item> 
    </element> 
</root> 

.xml文件,我想提取元素標籤的所有文字,所以結果我想「文本1文本2文本3文本4「。我怎樣才能做到這一點?

+0

http://developer.android.com/training/basics/network-ops/xml.html –

回答

1

您可以使用XmlPullParser來解析xml。

你可以找到更多信息@

http://developer.android.com/training/basics/network-ops/xml.html

要調用

new XMLPullParserHandler().parse(your input stream); 

然後

public class XMLPullParserHandler { 

    private String text; 

    public XMLPullParserHandler() { 

    } 
    public Void parse(InputStream is) { // input stream 
     XmlPullParserFactory factory = null; 
     XmlPullParser parser = null; 
     try { 
      factory = XmlPullParserFactory.newInstance(); 
      factory.setNamespaceAware(true); 
      parser = factory.newPullParser(); 

      parser.setInput(is, null); 


      //factory instantiates an object 

      int eventType = parser.getEventType(); 
      while (eventType != XmlPullParser.END_DOCUMENT) { 
       String tagname = parser.getName(); 
       switch (eventType) { 
       case XmlPullParser.START_TAG: 


        break; 

       case XmlPullParser.TEXT: 
        text = parser.getText(); 
        break; 

       case XmlPullParser.END_TAG: 
          String val = null; 
         if (tagname.equalsIgnoreCase("p")) { // tag p 

          val=text; // get the text 
          Log.i(""," text is "+val); 

         } 

        break; 

       default: 
        break; 
       } 
       eventType = parser.next(); 
      } 

     } catch (XmlPullParserException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 
} 

日誌

04-24 10:01:19.236: I/(1662): text is text 1 
04-24 10:01:19.236: I/(1662): text is text 2 
04-24 10:01:19.246: I/(1662): text is text 3 
04-24 10:01:19.256: I/(1662): text is text 4 

您也可以使用Dom解析器,Sax解析器。