1. 程式人生 > >XML基礎--DOM4J解析

XML基礎--DOM4J解析

dom4j解析

1.XML基礎概念

XML:可擴展標記語言
概念: 可擴展: 標簽名可以自己定義 <hehe></hehe> <呵呵></呵呵>
命名規範:不能用數字開頭 不能使用純數字 區分大小寫
功能:1.用作配置文件
2.用作網絡數據傳輸的載體 xml 用於PC端數據傳輸的載體
JSON {"username":"張三","age":23,"sex":"1"} 一般用於移動端的數據傳輸載體 因為他體積小
語法:新建一個文本文件 後綴名必須為 .xml

組成部分:
文檔聲明:<?xml version="1.0" encoding="utf-8"?>
endoing 寫的編碼是規定哪裏的編碼? 告訴瀏覽用什麽編碼去解析
文檔聲明:必須頂行寫,還有頂格寫。
根標簽:有且僅有一個根標簽
其他標簽 有開始標簽 一定要有結束標簽
文本:
CDATA區:該區域的文本,會按照純文本解析
格式: <![CDATA[ 內容 ]]>

2.解析XML
解析思想:

1)DOM: Document Object Model 文檔對象模型
DOM:將文檔的各個組成部分 抽取一個對象
Element 標簽對象
Attribute 屬性對象
Text 文本對象
Comment 註釋對象
Node 節點對象
Document· 文檔對象
怎麽解析:將文檔一次性 加載進內存 然後將文檔各個組成不封抽取為對象
優點: 能夠對文檔進行增刪改查

缺點:耗內存 適用於PC 端

2)SAX :基於事件 逐行解析,一次讀取一行,釋放一行
優點 :不占內存 適用於移動端
缺點:只能查 不能增刪改

3.解析器--DOM4J解析器

//創建解析器對象

SAXReader reader = new SAXReader();

//導入目標文件


1) 獲取根標簽對象
Element rootElement = doc.getRootElement();
// 獲取根標簽下的子標簽 默認獲取的是第一個子標簽
Element stuElement = rootElement.element("student");
System.out.println(stuElement.getName());
// 獲取所有的子標簽
List<Element> eles = rootElement.elements();
for (Element ele : eles) {
System.out.println(ele.getName());
}
// 方式三 通過叠代器獲取所有子標簽
Iterator<Element> elementIterator = rootElement.elementIterator();
while (elementIterator.hasNext()) {
Element element = elementIterator.next();
System.out.println(element.getName());

}

2)獲取屬性對象

Element element = rootElement.element("student");
Attribute attribute = element.attribute("id");
String value = attribute.getValue();
String name = attribute.getName();
System.out.println(name);
System.out.println(value);
// 方式2:直接獲取屬性值
String value2 = rootElement.element("student").attributeValue("id");
System.out.println(value2);
// 方式三:獲取所有的屬性對象
List<Attribute> attributes = rootElement.element("student").attributes();
for (Attribute atr : attributes) {
String name2 = atr.getName();
String value3 = atr.getValue();
System.out.println(name2 + "======" + value3);

}

叠代器獲取所有屬性對象
Iterator<Attribute> attributeIterator = rootElement.element("student").attributeIterator();
while(attributeIterator.hasNext()){
Attribute attribute2 = attributeIterator.next();
System.out.println(attribute2.getName()+"=="+attribute2.getValue());

}

3)獲取文本

//層層往下拿
String text = doc.getRootElement().element("student").element("name").getText();
System.out.println(text);
//方式2:
String text2 = doc.getRootElement().element("student").elementText("name");
System.out.println(text2);

4)獲取節點

private static void getNodes(Element ele) {
System.out.println(ele.getName());
Iterator<Node> iterator = ele.nodeIterator();
while (iterator.hasNext()) {
Node nodes = iterator.next();
if (nodes instanceof Element) {//
Element ele2 = (Element) nodes;
getNodes(ele2);

// 遞歸調用 方法內部調用方法本身 註意遞歸比較耗費資源,因為他要不斷的加載方法進棧內存
}
}
}

XML基礎--DOM4J解析