初识XML

XML

XML概述

使用XML文件,可以保存复杂的数据,数据结构清晰(树状结构)

传输数据是一种通用的数据格式
传递数据,作为配置文件存在

XML语法

版本
<?xml version="1.0"?>

用encoding属性说明文档所使用的字符编码,默认为UTF-8。保存在磁盘上的文件编码要与声明的编码一致。
<?xml version="1.0" encoding="UTF-8"?>

用standalone属性说明文档是否独立,即是否依赖其他文档。
<?xml version="1.0" standalone="yes"?>

标签的属性,描述该标签
<linkman 属性名="属性值">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<person id="1">
<name>蔡徐坤</name>
<address>荷兰</address>
<email>kk@nmsl</email>
<age>17</age>
</person>
<person id="2">
<name>孙笑川</name>
<address>日本</address>
<email>cc@nmsl</email>
<age>18</age>
</person>
</contacts>

DOM解析(Document Object Model)

文档对象模型,可以将xml的操作当做是操作对象

特点:

在加载XML文档的时候,会一次性把所有的信息加载到内存中(DOM树)
使用document这一对象来描述,剩下的操作都是操作内存中的对象

缺点:

如果XML文档内容比较多,文件比较大,一加载到内存中会导致,内存溢出

注意:

1.使用DOM解析,导入的类都是在org.w3c.dom包中.如果发现让你强转.意识到可能导错包了.
2.在XML中,一切皆节点

####获取Document对象

三个类

Document
DocumentBuilder
DocumentBuilderFactory

newDocumentBuilder:单例设计模式,需要通过自身的newInstance方法,获取一个新的实例

DocumentBuilder:需要通过newDocumentBuilder的实例中的newDocumentBuilder获取对象,该类重写了parse方法和newDocument方法

Document:接口,不能创建对象.抽象的parse方法和newDocument方法

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
package me.cscar.DOM.object;

import org.junit.Test;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.InputStream;

public class GetDOMObject {
@Test
public void getObject() throws Exception {
File file = new File("/Users/cscar/IdeaProjects/wolfCode/day03/resource/MyXML.xml");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.newDocument();

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML.xml");
Document doc1 = db.parse(is);

//Document doc = db.parse(file);

System.out.println(doc.equals(doc1));
}
}

####常用API(增删改查)
常用的API:

Document对象:
    Element getDocumentElement(): 获取根节点.
    Element getElementById(String elementId) :根据唯一ID获取节点.
Element对象:
    NodeList getElementsByTagName(String name):根据标签名获取到标签列表.
    String getAttribute(String name) :根据属性名,获取属性值
    void setAttribute(String name, String value) :设置属性名和属性值.
Node 对象:
    String getTextContent(): 返回当前节点的文本内容.
    void setTextContent(String value): 设置文本内容.

ADD

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
package me.cscar.DOM.frequently;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

public class Add {
@Test
public void useAdd() throws Exception {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML.xml");
//创建document对象
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
//获取根节点
Element element = doc.getDocumentElement();
//创建节点
Element person = doc.createElement("person");
person.setAttribute("id", "4");

Element name = doc.createElement("name");
Element email = doc.createElement("email");
Element address = doc.createElement("address");
Element age = doc.createElement("age");

//创建层级关系
element.appendChild(person);

person.appendChild(name);
person.appendChild(email);
person.appendChild(address);
person.appendChild(age);

//给节点设置数据
name.setTextContent("蛤蛤");
email.setTextContent("haha@china.com");
address.setTextContent("中国");
age.setTextContent("90");

SynchroFile.synchor(doc);

}
}

REMOVE

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
package me.cscar.DOM.frequently;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

/**
* 删除操作
*/
public class Remove {
@Test
public void useRemove() throws Exception {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML.xml");

//获取document对象
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

//获取根节点
Element de = doc.getDocumentElement();

//person标签
NodeList person = de.getElementsByTagName("person");

//获取第三个人的标签
Element p3 = (Element) person.item(2);
System.out.println(p3.getAttribute("id"));

p3.getParentNode().removeChild(p3);

//同步操作,把修改的document对象写入

SynchroFile.synchor(doc);

}
}

QUERY

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
package me.cscar.DOM.frequently;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

/**
* 查询操作
*/
public class Query {
@Test
public void useQuery() throws Exception {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML.xml");

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

Element de = doc.getDocumentElement();

//第1个人的信息节点
NodeList person = de.getElementsByTagName("person");
System.out.println("长度是"+person.getLength());
Element item = (Element) person.item(2);
//获取ID编号
//System.out.println(item.getAttribute("id"));

//找到第1个联系人的name节点
Element nameNode = (Element) item.getElementsByTagName("name").item(0);
int re = item.getElementsByTagName("name").getLength();
//System.out.println(re);
String name = nameNode.getTextContent();
System.out.println(name);

//获取所有人的信息
for (int i = 0; i < person.getLength(); i++) {
Element item1 = (Element) person.item(i);
String name1 = item1.getElementsByTagName("name").item(0).getTextContent();
String email = item1.getElementsByTagName("email").item(0).getTextContent();
String address = item1.getElementsByTagName("address").item(0).getTextContent();
String age = item1.getElementsByTagName("age").item(0).getTextContent();
System.out.println(name1 + '\n' + email + '\n' + address + '\n' + age);
System.out.println("-------------");
}
}
}

UPDATE

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
package me.cscar.DOM.frequently;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

/**
* 修改操作
*/
public class Update {
@Test
public void useUpdate() throws Exception {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML.xml");

//获取document对象
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
//获取根标签
Element element = doc.getDocumentElement();

//获取第3个人信息
Element person = (Element) element.getElementsByTagName("person").item(2);
//获取name标签
Element name = (Element) person.getElementsByTagName("name").item(0);

//修改name标签
name.setTextContent("包包");

//调用同步方法
SynchroFile.synchor(doc);

}
}

同步操作

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
package me.cscar.DOM.frequently;

import org.w3c.dom.Document;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.InputStream;

/**
* 增删改的同步操作
* 把修改的document真正写入
*/
public class SynchroFile {

public static void synchor(Document doc) throws Exception {

File file = new File("/Users/cscar/IdeaProjects/wolfCode/day03/resource/MyXML.xml");

//获取工厂对象
TransformerFactory factory = TransformerFactory.newInstance();
//获取转换器
Transformer transformer = factory.newTransformer();

//调用转换器中的方法
Source src = new DOMSource(doc);
Result target = new StreamResult(file);
transformer.transform(src, target);
}
}

创建新的XML

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
package me.cscar.DOM.create;

import me.cscar.DOM.frequently.SynchroFile;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class Create {
@Test
public void CreateDoc() throws Exception {
//File file = new File("/Users/cscar/IdeaProjects/wolfCode/day03/resource/MyXML.xml");
File newFile = new File("/Users/cscar/IdeaProjects/wolfCode/day03/resource/MyXML_Copy.xml");

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

//创建一个根节点
Element element = doc.createElement("contacts");
//添加根节点

doc.appendChild(element);

TransformerFactory factory = TransformerFactory.newInstance();
Transformer tf = factory.newTransformer();

Source src = new DOMSource(doc);
Result target = new StreamResult(newFile);
tf.transform(src, target);


}
}

####XML约束(了解)