DOM 操作XML(CRUD)

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
    <书>
        <书名 name="dddd">C语言程序设计</书名>
        <作者>张孝祥</作者>
        <售价>40</售价>
    </书>
    <书>
        <书名>C++教程</书名>
        <作者>自己</作者>
        <售价>50</售价>
    </书>
</书架>

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package com.gbx.it;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StreamCorruptedException;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class XMLDemo {
    public String path = "src/book.xml";
    /*
     * 获得指定的Document
     */
    public Document getDocument() throws ParserConfigurationException, SAXException, IOException {
        //1: 获得dom解析工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //2:获得dom解析
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        //获得Document
        Document document = documentBuilder.parse(path);
         
        return document;
    }
    /*
     * 将XML文件由内存写入硬盘
     */
    public void refreshXML(Source xmlSource, Result outputTarget) throws TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(xmlSource, outputTarget);
    }
    //   ----------R------------------
    /*
     * 遍历DOM树
     */
    @Test
    public void read1() throws ParserConfigurationException, SAXException, IOException {
        Document document = getDocument();
        NodeList nodeList = document.getElementsByTagName("书架");
        for (int i = 0; i < nodeList.getLength(); ++i) {
            listNodes(nodeList.item(i));
        }
    }
    private void listNodes(Node item) {
        if (item instanceof Element) {
            System.out.println(item.getNodeName());
        }
        NodeList nodeList = item.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); ++i) {
            listNodes(nodeList.item(i));
        }
    }
    /*
     * 读取标签内的内容 <书名 name="dddd">java web就业</书名> 
     */
    @Test
    public void read2() throws ParserConfigurationException, SAXException, IOException {
        Document document = getDocument();
        Element book = (Element) document.getElementsByTagName("书名").item(0);
        String value = book.getTextContent();
        System.out.println("书名: " + value);
    }
    /*
     * 读取标签的属性
     */
    @Test
    public void read3() throws ParserConfigurationException, SAXException, IOException {
        Document document = getDocument();
        Element book = (Element) document.getElementsByTagName("书名").item(0);
        if (book.hasAttributes()) {
            NamedNodeMap nodeMap = book.getAttributes();
            for (int i = 0; i < nodeMap.getLength(); ++i) {
                String attrName = nodeMap.item(i).getNodeName();
                String attrValue = nodeMap.item(i).getNodeValue();
                System.out.println("name : " + attrName + " value :" + attrValue);
            }
        }
         
        String value = book.getAttribute("name");
        System.out.println(value);
    }
    // ----------------C-------------------
     
    /*
     * 添加标签  C
     */
    //在指定标签的最后边添加标签
    @Test
    public void add1() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
        Element book = (Element) document.getElementsByTagName("书").item(0);
        Element newChild = document.createElement("你行");
        newChild.setTextContent("嘿嘿");
        book.appendChild(newChild);
         
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
    //在指定标签的指定位置添加标签
    @Test
    public void add2() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
        Element book = (Element) document.getElementsByTagName("书").item(0);
         
        Element newChild = document.createElement("你行");
        newChild.setTextContent("嘿嘿");
         
        Element refChild = (Element) document.getElementsByTagName("售价").item(0);
         
        book.insertBefore(newChild, refChild);
         
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
    //添加属性
    @Test
    public void add3() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
         
        Element e = (Element) document.getElementsByTagName("售价").item(0);
        e.setAttribute("value", "RMB");
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
    //----------------D----------------
    //删除标签
    @Test
    public void delElement() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
        Element element = (Element) document.getElementsByTagName("你行").item(0);
        element.getParentNode().removeChild(element);
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
    //删除标签的属性
     
    @Test
    public void delAttr() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
        Element element = (Element) document.getElementsByTagName("售价").item(0);
        element.removeAttribute("value");
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
    //-------------U------------
    @Test
    public void update() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Document document = getDocument();
        Element element = (Element) document.getElementsByTagName("书名").item(0);
        element.setTextContent("C语言程序设计");
        refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
    }
}

  

 

参考:方立勋老师视频

 

 

posted @   E_star  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· .NET中 泛型 + 依赖注入 的实现与应用
点击右上角即可分享
微信分享提示