2011-08-26 107 views

回答

0

您有幾種方法來解析XML,使用最廣泛的是SAX和DOM。選擇是相當戰略的。

這裏是SAX的一個簡短的說明:

  • 你會需要一些import S:

    import org.xml.sax.Attributes; 
    import org.xml.sax.SAXException; 
    import org.xml.sax.SAXParseException; 
    import org.xml.sax.helpers.DefaultHandler; 
    import android.util.Xml; 
    
  • 創建您自己的XML SAX DefaultHandler

    class MySaxHandler extends DefaultHandler { 
        // Override the methods of DefaultHandler that you need. 
        // See [this link][3] to see these methods. 
        // These methods are going to be called while the XML is read 
        // and will allow you doing what you need with the content. 
        // Two examples below: 
    
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
         // This is called each time an openeing XML tag is read. 
         // As the tagname is passed by parameter you know which tag it is. 
         // You also have the attributes of the tag. 
         // Example <mytag myelem="12"> will lead to a call of 
         // this method with the parameters: 
         // - localName = "mytag" 
         // - attributes = { "myelem", "12" } 
        } 
    
        public void characters(char[] ch, int start, int length) throws SAXException { 
         // This is called each time some text is read. 
         // As an example, if you have <myTag>blabla</myTag> 
         // this will be called with the parameter "blabla" 
         // Warning 1: this is also called when linebreaks are read and the linebreaks are passed 
         // Warning 2: you have to memorize the last open tag to determine what tag this text belongs to (I usually use a stack). 
        } 
    } 
    
  • 提取物將XML作爲StringEditText。讓我們把它xmlContent

  • 創建和初始化您的XML解析器:

    final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xmlContent.getBytes())); 
    final MySaxHandler handler = new MySaxHandler(); 
    
  • ,然後做出解析器讀取XML內容。這會導致您的MySaxHandler在讀數正在進行時調用其各種方法。

    Xml.parse(reader, handler); 
    
1

改變這一行:

xr.parse(new InputSource(sourceUrl.openStream())); 

String xmlString = editText.getText().toString(); 
StringReader reader = new StringReader(xmlString); 
xr.parse(new InputSource(reader));