一)Document介紹
API來源:在JDK中javax.xml.*包下
使用場景:
1、需要知道XML文檔所有結構
2、需要把文檔一些元素排序
3、文檔中的信息被多次使用的情況
優勢:由于Document是java中自帶的解析器,兼容性強
缺點:由于Document是一次性加載文檔信息,如果文檔太大,加載耗時長,不太適用
二)Document生成XML
實現步驟:
第一步:初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
第二步:創建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
第三步:構建一個Document實例
Document doc = builder.newDocument();
doc.setXmlStandalone(true);
standalone用來表示該文件是否呼叫其它外部的文件。若值是 ”yes” 表示沒有呼叫外部文件
第四步:創建一個根節點,名稱為root,并設置一些基本屬性
1
2
3
|
Element element = doc.createElement( "root" ); element.setAttribute( "attr" , "root" ); //設置節點屬性 childTwoTwo.setTextContent( "root attr" ); //設置標簽之間的內容 |
第五步:把節點添加到Document中,再創建一些子節點加入
doc.appendChild(element);
第六步:把構造的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
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
|
package com.oysept.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; 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.w3c.dom.Document; import org.w3c.dom.Element; /** * Document生成XML * @author ouyangjun */ public class CreateDocument { public static void main(String[] args) { // 執行Document生成XML方法 createDocument( new File( "E:\\person.xml" )); } public static void createDocument(File file) { try { // 初始化一個XML解析工廠 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 創建一個DocumentBuilder實例 DocumentBuilder builder = factory.newDocumentBuilder(); // 構建一個Document實例 Document doc = builder.newDocument(); doc.setXmlStandalone( true ); // standalone用來表示該文件是否呼叫其它外部的文件。若值是 ”yes” 表示沒有呼叫外部文件 // 創建一個根節點 // 說明: doc.createElement("元素名")、element.setAttribute("屬性名","屬性值")、element.setTextContent("標簽間內容") Element element = doc.createElement( "root" ); element.setAttribute( "attr" , "root" ); // 創建根節點第一個子節點 Element elementChildOne = doc.createElement( "person" ); elementChildOne.setAttribute( "attr" , "personOne" ); element.appendChild(elementChildOne); // 第一個子節點的第一個子節點 Element childOneOne = doc.createElement( "people" ); childOneOne.setAttribute( "attr" , "peopleOne" ); childOneOne.setTextContent( "attr peopleOne" ); elementChildOne.appendChild(childOneOne); // 第一個子節點的第二個子節點 Element childOneTwo = doc.createElement( "people" ); childOneTwo.setAttribute( "attr" , "peopleTwo" ); childOneTwo.setTextContent( "attr peopleTwo" ); elementChildOne.appendChild(childOneTwo); // 創建根節點第二個子節點 Element elementChildTwo = doc.createElement( "person" ); elementChildTwo.setAttribute( "attr" , "personTwo" ); element.appendChild(elementChildTwo); // 第二個子節點的第一個子節點 Element childTwoOne = doc.createElement( "people" ); childTwoOne.setAttribute( "attr" , "peopleOne" ); childTwoOne.setTextContent( "attr peopleOne" ); elementChildTwo.appendChild(childTwoOne); // 第二個子節點的第二個子節點 Element childTwoTwo = doc.createElement( "people" ); childTwoTwo.setAttribute( "attr" , "peopleTwo" ); childTwoTwo.setTextContent( "attr peopleTwo" ); elementChildTwo.appendChild(childTwoTwo); // 添加根節點 doc.appendChild(element); // 把構造的XML結構,寫入到具體的文件中 TransformerFactory formerFactory=TransformerFactory.newInstance(); Transformer transformer=formerFactory.newTransformer(); // 換行 transformer.setOutputProperty(OutputKeys.INDENT, "YES" ); // 文檔字符編碼 transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8" ); // 可隨意指定文件的后綴,效果一樣,但xml比較好解析,比如: E:\\person.txt等 transformer.transform( new DOMSource(doc), new StreamResult(file)); System.out.println( "XML CreateDocument success!" ); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } } |
XML文件效果圖:
三)Document解析XML
實現步驟:
第一步:先獲取需要解析的文件,判斷文件是否已經存在或有效
第二步:初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
第三步:創建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
第四步:創建一個解析XML的Document實例
Document doc = builder.parse(file);
第五步:先獲取根節點的信息,然后根據根節點遞歸一層層解析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
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
|
package com.oysept.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Attr; 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; /** * Document解析XML * @author ouyangjun */ public class ParseDocument { public static void main(String[] args){ File file = new File( "E:\\person.xml" ); if (!file.exists()) { System.out.println( "xml文件不存在,請確認!" ); } else { parseDocument(file); } } public static void parseDocument(File file) { try { // 初始化一個XML解析工廠 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 創建一個DocumentBuilder實例 DocumentBuilder builder = factory.newDocumentBuilder(); // 創建一個解析XML的Document實例 Document doc = builder.parse(file); // 獲取根節點名稱 String rootName = doc.getDocumentElement().getTagName(); System.out.println( "根節點: " + rootName); System.out.println( "遞歸解析--------------begin------------------" ); // 遞歸解析Element Element element = doc.getDocumentElement(); parseElement(element); System.out.println( "遞歸解析--------------end------------------" ); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 遞歸方法 public static void parseElement(Element element) { System.out.print( "<" + element.getTagName()); NamedNodeMap attris = element.getAttributes(); for ( int i = 0 ; i < attris.getLength(); i++) { Attr attr = (Attr) attris.item(i); System.out.print( " " + attr.getName() + "=\"" + attr.getValue() + "\"" ); } System.out.println( ">" ); NodeList nodeList = element.getChildNodes(); Node childNode; for ( int temp = 0 ; temp < nodeList.getLength(); temp++) { childNode = nodeList.item(temp); // 判斷是否屬于節點 if (childNode.getNodeType() == Node.ELEMENT_NODE) { // 判斷是否還有子節點 if (childNode.hasChildNodes()){ parseElement((Element) childNode); } else if (childNode.getNodeType() != Node.COMMENT_NODE) { System.out.print(childNode.getTextContent()); } } } System.out.println( "</" + element.getTagName() + ">" ); } } |
XML解析效果圖:
補充知識:Java——采用DOM4J+單例模式實現XML文件的讀取
大家對XML并不陌生,它是一種可擴展標記語言,常常在項目中作為配置文件被使用。XML具有高度擴展性,只要遵循一定的規則,XML的可擴展性幾乎是無限的,而且這種擴展并不以結構混亂或影響基礎配置為代價。項目中合理的使用配置文件可以大大提高系統的可擴展性,在不改變核心代碼的情況下,只需要改變配置文件就可以實現功能變更,這樣也符合編程開閉原則。
但是我們把數據或者信息寫到配置文件中,其他類或者模塊要怎樣讀取呢?這時候我們就需要用到XML API。 DOM4Jj就是一個十分優秀的JavaXML API,具有性能優異、功能強大和極其易使用的特點,下面我們就以java程序連接Oracle數據庫為例,簡單看一下如何使用配置文件提高程序的可擴展性以及DOM4J如何讀取配置文件。
未使用配置文件的程序
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
|
<span style= "font-family:KaiTi_GB2312;font-size:18px;" > /* * 封裝數據庫常用操作 */ public class DbUtil { /* * 取得connection */ public static Connection getConnection(){ Connection conn= null ; try { Class.forName( "oracle.jdbc.driver.OracleDriver" ); String url = "jdbc:oracle:thin:@localhost:1525:bjpowernode" ; String username = "drp1" ; String password = "drp1" ; conn=DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } }</span> |
我們可以看到上面代碼中DriverName、url等信息都是都是寫死在代碼中的,如果數據庫信息有變更的話我們必須修改DbUtil類,這樣的程序擴展性極低,是不可取的。
我們可以把DriverName、url等信息保存到配置文件中,這樣如果修改的話只需要修改配置文件就可以了,程序代碼根本不需要修改。
1
2
3
4
5
6
7
8
9
10
|
< span style = "font-family:KaiTi_GB2312;font-size:18px;" ><? xml version = "1.0" encoding = "UTF-8" ?> < config > < db-info > < driver-name >oracle.jdbc.driver.OracleDriver</ driver-name > < url >jdbc:oracle:thin:@localhost:1525:bjpowernode</ url > < user-name >drp1</ user-name > < password >drp1</ password > </ db-info > </ config > </ span > |
然后我們還需要建立一個配置信息類來用來存取我們的屬性值
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
|
<span style= "font-family:KaiTi_GB2312;font-size:18px;" > /* * jdbc配置信息 */ public class JdbcConfig { private String driverName; private String url; private String userName; private String password; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this .driverName = driverName; } public String getUrl() { return url; } public void setUrl(String url) { this .url = url; } public String getUserName() { return userName; } public void setUserName(String userName) { this .userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } @Override public String toString() { // TODO Auto-generated method stub return this .getClass().getName()+ "{driverName:" + driverName + ",url:" + url + ",userName:" + userName + "}" ; } }</span> |
接下來就是用DOM4J讀取XML信息,并把相應的屬性值保存到JdbcConfig中
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
|
<span style= "font-family:KaiTi_GB2312;font-size:18px;" > /* * DOM4J+單例模式解析sys-config.xml文件 */ public class XmlConfigReader { //懶漢式(延遲加載lazy) private static XmlConfigReader instance=null; //保存jdbc相關配置信息 private JdbcConfig jdbcConfig=new JdbcConfig(); private XmlConfigReader(){ SAXReader reader=new SAXReader(); InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml"); try { Document doc=reader.read(in); //取得jdbc相關配置信息 Element driverNameElt=(Element)doc.selectObject("/config/db-info/driver-name"); Element urlElt=(Element)doc.selectObject("/config/db-info/url"); Element userNameElt=(Element)doc.selectObject("/config/db-info/user-name"); Element passwordElt=(Element)doc.selectObject("/config/db-info/password"); //設置jdbc相關配置信息 jdbcConfig.setDriverName(driverNameElt.getStringValue()); jdbcConfig.setUrl(urlElt.getStringValue()); jdbcConfig.setUserName(userNameElt.getStringValue()); jdbcConfig.setPassword(passwordElt.getStringValue()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static synchronized XmlConfigReader getInstance(){ if (instance==null){ instance=new XmlConfigReader(); } return instance; } /* * 返回jdbc相關配置 */ public JdbcConfig getJdbcConfig(){ return jdbcConfig; } public static void main(String[] args){ JdbcConfig jdbcConfig=XmlConfigReader.getInstance().getJdbcConfig(); System.out.println(jdbcConfig); } }</span> |
然后我們的數據庫操作類就可以使用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
|
<span style= "font-family:KaiTi_GB2312;font-size:18px;" > /* * 封裝數據庫常用操作 */ public class DbUtil { /* * 取得connection */ public static Connection getConnection(){ Connection conn= null ; try { JdbcConfig jdbcConfig=XmlConfigReader.getInstance().getJdbcConfig(); Class.forName(jdbcConfig.getDriverName()); conn=DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUserName(), jdbcConfig.getPassword()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } } </span> |
現在我們可以看出來DriverName、url等信息都是通過jdbcConfig直接獲得的,而jdbcConfig中的數據是通過DOM4J讀取的XML,這樣數據庫信息有變動我們只需要通過記事本修改XML文件整個系統就可以繼續運行,真正做到了程序的可擴展,以不變應萬變。
以上這篇Java Document生成和解析XML操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/p812438109/article/details/81807440