Android使用DOM產生和輸出XML格式資料

來源:互聯網
上載者:User

Android使用DOM產生和輸出XML格式資料
Android使用DOM產生和輸出XML格式資料

本文主要簡單講解如何使用DOM產生和輸出XML資料。

1. 產生和輸出XML資料

代碼及注釋如下:

try {        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        DocumentBuilder builder = factory.newDocumentBuilder();        //建立一個新的Document對象,並非擷取        Document xmlDocument = builder.newDocument();        //建立根節點並添加屬性值        Element root = xmlDocument.createElement("Languages");        root.setAttribute("foo", "bar");        /**         * 建立第一個元素節點         */        //建立相應的元素節點,並添加屬性值和常值內容        Element lan_1 = xmlDocument.createElement("lan");        lan_1.setAttribute("id", "1");        Element name_1 = xmlDocument.createElement("name");        name_1.setTextContent("Java");        Element ide_1 = xmlDocument.createElement("ide");        ide_1.setTextContent("Eclipse");        //將name標籤和ide標籤添加到lan標籤內        lan_1.appendChild(name_1);        lan_1.appendChild(ide_1);        //將lan標籤添加到Languages標籤內        root.appendChild(lan_1);        /**         * 建立第二個元素節點         */        //建立相應的元素節點,並添加屬性值和常值內容        Element lan_2 = xmlDocument.createElement("lan");        lan_2.setAttribute("id", "2");        Element name_2 = xmlDocument.createElement("name");        name_2.setTextContent("Swift");        Element ide_2 = xmlDocument.createElement("ide");        ide_2.setTextContent("XCode");        //將name標籤和ide標籤添加到lan標籤內        lan_2.appendChild(name_2);        lan_2.appendChild(ide_2);        //將lan標籤添加到Languages標籤內        root.appendChild(lan_2);        //將根節點添加進Document文檔對象中        xmlDocument.appendChild(root);        //對XML資料進行輸出需要進行轉換,使用Transformer        TransformerFactory transformerFactory = TransformerFactory.newInstance();        Transformer transformer = transformerFactory.newTransformer();        //設定輸出屬性        transformer.setOutputProperty("encoding", "UTF-8");        //建立新的字元輸出資料流用於輸出資料        StringWriter stringWriter = new StringWriter();        //對XML文檔 對象進行轉換並輸出到輸出資料流中        transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter));        Log.i("XMLDATA", stringWriter.toString());    } catch (ParserConfigurationException e) {        e.printStackTrace();    } catch (TransformerConfigurationException e) {        e.printStackTrace();    } catch (TransformerException e) {        e.printStackTrace();    }

聯繫我們

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