Android備忘錄,留著自用,高手勿笑:(三)XML

來源:互聯網
上載者:User

解析XML,Android有兩種法師,SAX方式(流和事件,使用比較大的XML,比較要求效能的),DOM方式(整個檔案載入並解析完畢,提供介面操作,使用小的XML,不要求效能的)。

 

程式碼片段:

SAX:

import javax.xml.parsers.SAXParserFactory 
import javax.xml.parsers.SAXParser 

//

SAXParserFactory factory = SAXParserFactory.newInstance(); 
SAXParser parser = factory.newSAXParser(); 
ParseXML parX = new ParseXML(); 
parser.parse("F:\\emps.xml", parX);

 

DOM:

import javax.xml.parsers.DocumentBuilderFactory 
import javax.xml.parsers.DocumentBuilder 
//
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
doc = db.parse(docFile); // get the document. 

 

我經常使用DOM,下面的例子代碼:

 1             InputStream kana = this._activity.getResources().getAssets().open(_fileName);
2 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(kana);
3 Element root = doc.getDocumentElement(); //得到根節點
4 NodeList lstNodes = root.getElementsByTagName(yin).item(0).getChildNodes();
5 //
6   for(int i= 0; i< lstNodes.getLength(); i++)
7 {  //因為還有空節點,轉化前注意結點的類型。
8 if(lstNodes.item(i).getNodeType() == Node.ELEMENT_NODE)
9 {
10 Element el = (Element)lstNodes.item(i);
11 KanaXml temp = new KanaXml();
12 temp.Hiragana = el.getAttribute(_hiragana);
13 temp.Katakana = el.getAttribute(_katakana);
14 temp.Romaji = el.getAttribute(_romaji);
15 temp.Sound = el.getAttribute(_sound);
16 lstXmls.add(temp);
17 }
18 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.