xml檔案
<?xml version="1.0" encoding="utf-8" ?><class><student><firstname>cxx1firstname><lastname>Bob1lastname><nickname>stars1nickname><marks>85marks>student><student rollno="493"><firstname>cxx2firstname><lastname>Bob2lastname><nickname>stars2nickname><marks>85marks>student><student rollno="593"><firstname>cxx3firstname><lastname>Bob3lastname><nickname>stars3nickname><marks>85marks>student>class>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
1.DOM方式
package com.cxx.xml;import org.w3c.dom.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;/**
* @Author: cxx
* Dom操作xml
* @Date: 2018/5/29 20:19
*/public class DomDemo {//用Element方式public static void element(NodeList list){for (int i = 0; i Element element = (Element) list.item(i);
NodeList childNodes = element.getChildNodes();for (int j = 0; j if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {//擷取節點
System.out.print(childNodes.item(j).getNodeName() + ":");//擷取節點值
System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}
}public static void node(NodeList list){for (int i = 0; i Node node = list.item(i);
NodeList childNodes = node.getChildNodes();for (int j = 0; j if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {
System.out.print(childNodes.item(j).getNodeName() + ":");
System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}
}public static void main(String[] args) {//1.建立DocumentBuilderFactory對象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//2.建立DocumentBuilder對象try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document d = builder.parse("src/main/resources/demo.xml");
NodeList sList = d.getElementsByTagName("student");//element(sList);
node(sList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 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
結果截圖
2.SAX方式
package com.cxx.xml;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;/**
* @Author: cxx
* SAX解析DOM
* 一行一行 Handler
* startElement
* endElement
* @Date: 2018/5/29 20:03
*/public class SaxDemo {public static void main(String[] args) throws Exception {//1.或去SAXParserFactory執行個體
SAXParserFactory factory = SAXParserFactory.newInstance();//2.擷取SAXparser執行個體
SAXParser saxParser = factory.newSAXParser();//建立Handel對象
SAXDemoHandel handel = new SAXDemoHandel();
saxParser.parse("src/main/resources/demo.xml",handel);
}
}
class SAXDemoHandel extends DefaultHandler {//周遊xml檔案開始标簽@Overridepublic void startDocument() throws SAXException {super.startDocument();
System.out.println("sax解析開始");
}//周遊xml檔案結束标簽@Overridepublic void endDocument() throws SAXException {super.endDocument();
System.out.println("sax解析結束");
}@Overridepublic void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {super.startElement(uri, localName, qName, attributes);if (qName.equals("student")){
System.out.println("============開始周遊student=============");//System.out.println(attributes.getValue("rollno"));
}else if (!qName.equals("student")&&!qName.equals("class")){
System.out.print("節點名稱:"+qName+"----");
}
}@Overridepublic void endElement(String uri, String localName, String qName) throws SAXException {super.endElement(uri, localName, qName);if (qName.equals("student")){
System.out.println(qName+"周遊結束");
System.out.println("============結束周遊student=============");
}
}@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {super.characters(ch, start, length);
String value = new String(ch,start,length).trim();if (!value.equals("")) {
System.out.println(value);
}
}
}
- 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
結果截圖
3.JDOM方式
<dependency><groupId>org.jdomgroupId><artifactId>jdomartifactId><version>1.1.3version>dependency>
- 1
- 2
- 3
- 4
- 5
- 6
package com.cxx.xml;import org.jdom.Attribute;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.util.List;/**
* @Author: cxx
* JDom解析xml
* 快速開發XML應用程式。
* 是一個開源項目
* JDOM主要用來彌補DOM和SAX在實際應用當中的不足。
* @Date: 2018/5/30 11:44
*/public class JDomDemo {public static void main(String[] args) throws Exception {//1.建立SAXBuilder對象
SAXBuilder saxBuilder = new SAXBuilder();//2.建立輸入流
InputStream is = new FileInputStream(new File("src/main/resources/demo.xml"));//3.将輸入流加載到build中
Document document = saxBuilder.build(is);//4.擷取根節點
Element rootElement = document.getRootElement();//5.擷取子節點
List children = rootElement.getChildren();for (Element child : children) {
System.out.println("通過rollno擷取屬性值:"+child.getAttribute("rollno"));
List attributes = child.getAttributes();//列印屬性for (Attribute attr : attributes) {
System.out.println(attr.getName()+":"+attr.getValue());
}
List childrenList = child.getChildren();
System.out.println("======擷取子節點-start======");for (Element o : childrenList) {
System.out.println("節點名:"+o.getName()+"---"+"節點值:"+o.getValue());
}
System.out.println("======擷取子節點-end======");
}
}
}
- 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
結果截圖
4.DOM4J方式
<dependency><groupId>dom4jgroupId><artifactId>dom4jartifactId><version>1.6.1version>dependency>
- 1
- 2
- 3
- 4
- 5
- 6
package com.cxx.xml;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import java.io.File;import java.util.Iterator;import java.util.List;/**
* @Author: cxx
* Dom4j解析xml
* @Date: 2018/5/30 12:21
*/public class Dom4JDemo {public static void main(String[] args) throws Exception {//1.建立Reader對象
SAXReader reader = new SAXReader();//2.加載xml
Document document = reader.read(new File("src/main/resources/demo.xml"));//3.擷取根節點
Element rootElement = document.getRootElement();
Iterator iterator = rootElement.elementIterator();while (iterator.hasNext()){
Element stu = (Element) iterator.next();
List attributes = stu.attributes();
System.out.println("======擷取屬性值======");for (Attribute attribute : attributes) {
System.out.println(attribute.getValue());
}
System.out.println("======周遊子節點======");
Iterator iterator1 = stu.elementIterator();while (iterator1.hasNext()){
Element stuChild = (Element) iterator1.next();
System.out.println("節點名:"+stuChild.getName()+"---節點值:"+stuChild.getStringValue());
}
}
}
}
- 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
總結
比較
1)DOM4J性能最好,連Sun的JAXM也在用DOM4J.目前許多開源項目中大量采用DOM4J,例如大名鼎鼎的Hibernate也用DOM4J來讀取XML配置檔案。如果不考慮可移植性,那就采用DOM4J.
2)JDOM和DOM在性能測試時表現不佳,在測試10M文檔時記憶體溢出。在小文檔情況下還值得考慮使用DOM和JDOM.雖然JDOM的開發者已經說明 他們期望在正式發行版前專注性能問題,但是從性能觀點來看,它确實沒有值得推薦之處。另外,DOM仍是一個非常好的選擇。DOM實作廣泛應用于多種程式設計語 言。它還是許多其它與XML相關的标準的基礎,因為它正式獲得W3C推薦(與基于非标準的Java模型相對),是以在某些類型的項目中可能也需要它(如在 javascript中使用DOM)。
3)SAX表現較好,這要依賴于它特定的解析方式-事件驅動。一個SAX檢測即将到來的XML流,但并沒有載入到記憶體(當然當XML流被讀入時,會有部分文檔暫時隐藏在記憶體中)。
運作時如果有錯誤可能原因
1.錯誤現象: Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
解決辦法:xml檔案換行問題,編寫xml檔案時不要換行就可以了.
2.dom4j
錯誤現象: org.dom4j.DocumentException: Error on line 1 of document : Content is not allowed in prolog.
解決方法:dom4j的jar包使用dom4j1.6就可以了.
參考:
https://blog.csdn.net/m0_37499059/article/details/80505567
https://blog.csdn.net/wangliyingligong/article/details/4161941
https://blog.csdn.net/weixin_33755554/article/details/93080091