Android學習筆記---Android平台1.使用dom解析xml檔案

來源:互聯網
上載者:User

1.使用dom解析xml檔案除了使用 SAX可以解析XML檔案,大家也可以使用熟悉的DOM來解析XML檔案。 DOM解析XML文  件時,會將XML檔案的所有內容以文檔樹方式存放在記憶體中,然後允許您使用DOM API遍曆XML  樹、檢索所需的資料。使用DOM操作XML的代碼看起來是比較直觀的,並且在編碼方面比基於  SAX的實現更加簡單。但是,因為DOM需要將XML檔案的所有內容以文檔樹方式存放在記憶體中,  所以記憶體的消耗比較大,特別對於運行Android的行動裝置來說,因為裝置的資源比較寶貴,  所以建議還是採用SAX來解析XML檔案,當然,如果XML檔案的內容比較小採用DOM也是可行的代碼請看本頁下方備忘import java.io.InputStream;import java.util.ArrayList;import java.util.List;  import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;  import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;  import cn.itcast.xml.domain.Person;/** * 使用Dom解析xml檔案 * */public class DomXMLReader {  public static List readXML(InputStream inStream) {List persons = new ArrayList();DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();try {DocumentBuilder builder = factory.newDocumentBuilder();Document dom = builder.parse(inStream);Element root = dom.getDocumentElement();NodeList items = root.getElementsByTagName("person");//尋找所有  person節點for (int i = 0; i < items.getLength(); i++) {Person person = new Person();//得到第一個person節點Element personNode = (Element) items.item(i);//擷取person節點的id屬性值person.setId(new Integer(personNode.getAttribute("id")));//擷取person節點下的所有子節點(標籤之間的空白節點和  name/age元素)NodeList childsNodes = personNode.getChildNodes();for (int j = 0; j < childsNodes.getLength(); j++) {Node node = (Node) childsNodes.item(j);    //判斷是否為元素類型if(node.getNodeType() == Node.ELEMENT_NODE){      Element childNode = (Element) node;                                        //判斷是否name元素   if ("name".equals(childNode.getNodeName())) {    //擷取name元素下Text節點,然後從Text節點擷取資料         person.setName(childNode.getFirstChild  ().getNodeValue());   } else if (“age”.equals(childNode.getNodeName())) {person.setAge(new Short(childNode.getFirstChild  ().getNodeValue()));   }}       }   persons.add(person);}inStream.close();} catch (Exception e) {e.printStackTrace();}return persons;}----------------------------------------------------------

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.