2013-08-07 102 views
0

我有一個XML文件,我通過SAXParser讀取,但我無法正確讀取它。 XML的結構是這樣的:Android SAXParse獲取標籤之間的值

<game> 
    <players> 
    <player> 
     <name>Player 1</name> 
     <score>100</score> 
    </player> 
    </players> 
</game> 

我怎樣才能讓Android SAXParser讀取標籤之間的值?這是我有的代碼,但它正在尋找標籤的屬性,而不是之間的文本。從示例

@Override 
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 

    if(localName.equals("name")) { 
     names.add(attributes.getValue("name")); 
    } 
    else if(localName.equals("score")) {  
     scores.add(Integer.parseInt(attributes.getValue("score"))); 
    } 

} 

回答

0

繪圖@約薩克斯

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

更多信息@

http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

除了薩克斯你應該有哪些建議看看xmllpullparser。

從文檔引用。

我們推薦XmlPullParser,它是一種高效且可維護的方式來解析Android上的XML

檢查鏈接@

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

public void readxml(){ 
     try { 

     SAXParserFactory factory = SAXParserFactory.newInstance(); 
     SAXParser saxParser = factory.newSAXParser(); 

     DefaultHandler handler = new DefaultHandler() { 

     boolean bname = false; 
     boolean bscore = false; 


     public void startElement(String uri, String localName,String qName, 
        Attributes attributes) throws SAXException { 

      if (qName.equalsIgnoreCase("name")) { 
       bname = true; 
      } 

      if (qName.equalsIgnoreCase("score")) { 
       bscore = true; 
      } 
     } 

     public void endElement(String uri, String localName, 
      String qName) throws SAXException { 

     } 

     public void characters(char ch[], int start, int length) throws SAXException { 

      if (bname) { 
       Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show(); 
       bname = false; 
      } 

      if (bscore) { 
       Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show(); 
       bscore = false; 
      } 
     } 
     }; 

      saxParser.parse("myxmltoparse", handler); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     } 
}