java 解析 xml (DOM方法全)

來源:互聯網
上載者:User

標籤:

Java 處理 XML 的三種主流技術及介紹 http://www.ibm.com/developerworks/cn/xml/dm-1208gub/ 

這篇文章講的比較詳細,下面我主要介紹 dom方法 對xml檔案的增刪改操作。

參見http://blog.csdn.net/smcwwh/article/details/7183869 但由於排版有點亂,我整理下我需要的,作為以後的筆記吧。。。

DOM 最大的特點是:實現 W3C 標準,有多種程式設計語言支援這種解析方式,並且這種方法本身操作上簡單快捷,十分易於初學者掌握。其處理方式是將 XML 整個作為類似樹結構的方式讀入記憶體中以便操作及解析,因此支援應用程式對 XML 資料的內容和結構進行修改,但是同時由於其需要在處理開始時將整個 XML 檔案讀入到記憶體中去進行分析,因此其在解析大資料量的 XML 檔案時會遇到類似於記憶體泄露以及程式崩潰的風險,請對這點多加註意。

適用範圍:小型 XML 檔案解析、需要全解析或者大部分解析 XML、需要修改 XML 樹內容以產生自己的物件模型

下文代碼用到的xml資料來源

<?xml version="1.0" encoding="UTF-8"?><university name="pku">    <college name="c1">        <class name="class1">            <student name="stu1" sex=‘male‘ age="21" />            <student name="stu2" sex=‘female‘ age="20" />            <student name="stu3" sex=‘female‘ age="20" />        </class>        <class name="class2">            <student name="stu4" sex=‘male‘ age="19" />            <student name="stu5" sex=‘female‘ age="20" />            <student name="stu6" sex=‘female‘ age="21" />        </class>    </college>    <college name="c2">        <class name="class3">            <student name="stu7" sex=‘male‘ age="20" />        </class>    </college>    <college name="c3">    </college></university>
View Code

 

讀檔案

 public static void read() {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = dbf.newDocumentBuilder();            InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");//檔案名稱            Document doc = builder.parse(in);            // root <university>            Element root = doc.getDocumentElement();            if (root == null) return;            System.err.println(root.getAttribute("name"));            // all college node            NodeList collegeNodes = root.getChildNodes();            if (collegeNodes == null) return;            for(int i = 0; i < collegeNodes.getLength(); i++) {                Node college = collegeNodes.item(i);                if (college != null && college.getNodeType() == Node.ELEMENT_NODE) {                    System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue());                    // all class node                    NodeList classNodes = college.getChildNodes();                    if (classNodes == null) continue;                    for (int j = 0; j < classNodes.getLength(); j++) {                        Node clazz = classNodes.item(j);                        if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) {                            System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue());                            // all student node                            NodeList studentNodes = clazz.getChildNodes();                            if (studentNodes == null) continue;                            for (int k = 0; k < studentNodes.getLength(); k++) {                                Node student = studentNodes.item(k);                                if (student != null && student.getNodeType() == Node.ELEMENT_NODE) {                                    System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue());                                    System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue());                                    System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue());                                }                            }                        }                    }                }            }        } catch (ParserConfigurationException e) {            e.printStackTrace();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (SAXException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }            }
View Code

 

修改節點並將其寫入檔案

   public static void write() {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = dbf.newDocumentBuilder();            InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");            Document doc = builder.parse(in);            // root <university>            Element root = doc.getDocumentElement();            if (root == null) return;            // 修改屬性            root.setAttribute("name", "tsu");            NodeList collegeNodes = root.getChildNodes();            if (collegeNodes != null) {                for (int i = 0; i <collegeNodes.getLength() - 1; i++) {                    // 刪除節點                    Node college = collegeNodes.item(i);                    if (college.getNodeType() == Node.ELEMENT_NODE) {                        String collegeName = college.getAttributes().getNamedItem("name").getNodeValue();                        if ("c1".equals(collegeName) || "c2".equals(collegeName)) {                            root.removeChild(college);                        } else if ("c3".equals(collegeName)) {                            Element newChild = doc.createElement("class");                            newChild.setAttribute("name", "c4");                            college.appendChild(newChild);                        }                    }                }            }            // 新增節點            Element addCollege = doc.createElement("college");            addCollege.setAttribute("name", "c5");            root.appendChild(addCollege);            Text text = doc.createTextNode("text");            addCollege.appendChild(text);                        // 將修改後的文檔儲存到檔案            TransformerFactory transFactory = TransformerFactory.newInstance();            Transformer transFormer = transFactory.newTransformer();            DOMSource domSource = new DOMSource(doc);            File file = new File("src/dom-modify.xml");            if (file.exists()) {                file.delete();            }            file.createNewFile();            FileOutputStream out = new FileOutputStream(file);                     StreamResult xmlResult = new StreamResult(out);            transFormer.transform(domSource, xmlResult);            System.out.println(file.getAbsolutePath());        } catch (ParserConfigurationException e) {            e.printStackTrace();        } catch (SAXException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (TransformerConfigurationException e) {            e.printStackTrace();        } catch (TransformerException e) {            e.printStackTrace();        }    }}
View Code

 

java 解析 xml (DOM方法全)

聯繫我們

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