Java Document生成和解析XML操作
一)Document介紹
API來源:在JDK中javax.xml.*包下
使用場景:
1、需要知道XML文檔所有結(jié)構(gòu)
2、需要把文檔一些元素排序
3、文檔中的信息被多次使用的情況
優(yōu)勢:由于Document是java中自帶的解析器,兼容性強(qiáng)
缺點:由于Document是一次性加載文檔信息,如果文檔太大,加載耗時長,不太適用
二)Document生成XML
實現(xiàn)步驟:
第一步:初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
第二步:創(chuàng)建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
第三步:構(gòu)建一個Document實例
Document doc = builder.newDocument();
doc.setXmlStandalone(true);
standalone用來表示該文件是否呼叫其它外部的文件。若值是 ”yes” 表示沒有呼叫外部文件
第四步:創(chuàng)建一個根節(jié)點,名稱為root,并設(shè)置一些基本屬性
Element element = doc.createElement("root");
element.setAttribute("attr", "root");//設(shè)置節(jié)點屬性
childTwoTwo.setTextContent("root attr");//設(shè)置標(biāo)簽之間的內(nèi)容
第五步:把節(jié)點添加到Document中,再創(chuàng)建一些子節(jié)點加入
doc.appendChild(element);
第六步:把構(gòu)造的XML結(jié)構(gòu),寫入到具體的文件中
實現(xiàn)源碼:
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) {
// 執(zhí)行Document生成XML方法
createDocument(new File("E:\\person.xml"));
}
public static void createDocument(File file) {
try {
// 初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 創(chuàng)建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
// 構(gòu)建一個Document實例
Document doc = builder.newDocument();
doc.setXmlStandalone(true);
// standalone用來表示該文件是否呼叫其它外部的文件。若值是 ”yes” 表示沒有呼叫外部文件
// 創(chuàng)建一個根節(jié)點
// 說明: doc.createElement("元素名")、element.setAttribute("屬性名","屬性值")、element.setTextContent("標(biāo)簽間內(nèi)容")
Element element = doc.createElement("root");
element.setAttribute("attr", "root");
// 創(chuàng)建根節(jié)點第一個子節(jié)點
Element elementChildOne = doc.createElement("person");
elementChildOne.setAttribute("attr", "personOne");
element.appendChild(elementChildOne);
// 第一個子節(jié)點的第一個子節(jié)點
Element childOneOne = doc.createElement("people");
childOneOne.setAttribute("attr", "peopleOne");
childOneOne.setTextContent("attr peopleOne");
elementChildOne.appendChild(childOneOne);
// 第一個子節(jié)點的第二個子節(jié)點
Element childOneTwo = doc.createElement("people");
childOneTwo.setAttribute("attr", "peopleTwo");
childOneTwo.setTextContent("attr peopleTwo");
elementChildOne.appendChild(childOneTwo);
// 創(chuàng)建根節(jié)點第二個子節(jié)點
Element elementChildTwo = doc.createElement("person");
elementChildTwo.setAttribute("attr", "personTwo");
element.appendChild(elementChildTwo);
// 第二個子節(jié)點的第一個子節(jié)點
Element childTwoOne = doc.createElement("people");
childTwoOne.setAttribute("attr", "peopleOne");
childTwoOne.setTextContent("attr peopleOne");
elementChildTwo.appendChild(childTwoOne);
// 第二個子節(jié)點的第二個子節(jié)點
Element childTwoTwo = doc.createElement("people");
childTwoTwo.setAttribute("attr", "peopleTwo");
childTwoTwo.setTextContent("attr peopleTwo");
elementChildTwo.appendChild(childTwoTwo);
// 添加根節(jié)點
doc.appendChild(element);
// 把構(gòu)造的XML結(jié)構(gòu),寫入到具體的文件中
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
實現(xiàn)步驟:
第一步:先獲取需要解析的文件,判斷文件是否已經(jīng)存在或有效
第二步:初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
第三步:創(chuàng)建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
第四步:創(chuàng)建一個解析XML的Document實例
Document doc = builder.parse(file);
第五步:先獲取根節(jié)點的信息,然后根據(jù)根節(jié)點遞歸一層層解析XML
實現(xiàn)源碼:
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文件不存在,請確認(rèn)!");
} else {
parseDocument(file);
}
}
public static void parseDocument(File file) {
try{
// 初始化一個XML解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 創(chuàng)建一個DocumentBuilder實例
DocumentBuilder builder = factory.newDocumentBuilder();
// 創(chuàng)建一個解析XML的Document實例
Document doc = builder.parse(file);
// 獲取根節(jié)點名稱
String rootName = doc.getDocumentElement().getTagName();
System.out.println("根節(jié)點: " + 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);
// 判斷是否屬于節(jié)點
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
// 判斷是否還有子節(jié)點
if(childNode.hasChildNodes()){
parseElement((Element) childNode);
} else if (childNode.getNodeType() != Node.COMMENT_NODE) {
System.out.print(childNode.getTextContent());
}
}
}
System.out.println("</" + element.getTagName() + ">");
}
}
XML解析效果圖:

補(bǔ)充知識:Java——采用DOM4J+單例模式實現(xiàn)XML文件的讀取
大家對XML并不陌生,它是一種可擴(kuò)展標(biāo)記語言,常常在項目中作為配置文件被使用。XML具有高度擴(kuò)展性,只要遵循一定的規(guī)則,XML的可擴(kuò)展性幾乎是無限的,而且這種擴(kuò)展并不以結(jié)構(gòu)混亂或影響基礎(chǔ)配置為代價。項目中合理的使用配置文件可以大大提高系統(tǒng)的可擴(kuò)展性,在不改變核心代碼的情況下,只需要改變配置文件就可以實現(xiàn)功能變更,這樣也符合編程開閉原則。
但是我們把數(shù)據(jù)或者信息寫到配置文件中,其他類或者模塊要怎樣讀取呢?這時候我們就需要用到XML API。 DOM4Jj就是一個十分優(yōu)秀的JavaXML API,具有性能優(yōu)異、功能強(qiáng)大和極其易使用的特點,下面我們就以java程序連接Oracle數(shù)據(jù)庫為例,簡單看一下如何使用配置文件提高程序的可擴(kuò)展性以及DOM4J如何讀取配置文件。
未使用配置文件的程序
<span style="font-family:KaiTi_GB2312;font-size:18px;">/*
* 封裝數(shù)據(jù)庫常用操作
*/
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等信息都是都是寫死在代碼中的,如果數(shù)據(jù)庫信息有變更的話我們必須修改DbUtil類,這樣的程序擴(kuò)展性極低,是不可取的。
我們可以把DriverName、url等信息保存到配置文件中,這樣如果修改的話只需要修改配置文件就可以了,程序代碼根本不需要修改。
<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>
然后我們還需要建立一個配置信息類來用來存取我們的屬性值
<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信息,并把相應(yīng)的屬性值保存到JdbcConfig中
<span style="font-family:KaiTi_GB2312;font-size:18px;">/*
* DOM4J+單例模式解析sys-config.xml文件
*/
public class XmlConfigReader {
//懶漢式(延遲加載lazy)
private static XmlConfigReader instance=null;
//保存jdbc相關(guān)配置信息
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相關(guān)配置信息
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");
//設(shè)置jdbc相關(guān)配置信息
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相關(guān)配置
*/
public JdbcConfig getJdbcConfig(){
return jdbcConfig;
}
public static void main(String[] args){
JdbcConfig jdbcConfig=XmlConfigReader.getInstance().getJdbcConfig();
System.out.println(jdbcConfig);
}
}</span>
然后我們的數(shù)據(jù)庫操作類就可以使用XML文件中的屬性值了
<span style="font-family:KaiTi_GB2312;font-size:18px;">/*
* 封裝數(shù)據(jù)庫常用操作
*/
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>
現(xiàn)在我們可以看出來DriverName、url等信息都是通過jdbcConfig直接獲得的,而jdbcConfig中的數(shù)據(jù)是通過DOM4J讀取的XML,這樣數(shù)據(jù)庫信息有變動我們只需要通過記事本修改XML文件整個系統(tǒng)就可以繼續(xù)運(yùn)行,真正做到了程序的可擴(kuò)展,以不變應(yīng)萬變。
以上這篇Java Document生成和解析XML操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java中用數(shù)組實現(xiàn)環(huán)形隊列的示例代碼
這篇文章主要介紹了java中用數(shù)組實現(xiàn)環(huán)形隊列的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
解決Springboot2.1.x配置Activiti7單獨(dú)數(shù)據(jù)源問題
這篇文章主要介紹了Springboot2.1.x配置Activiti7單獨(dú)數(shù)據(jù)源問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
java web中 HttpClient模擬瀏覽器登錄后發(fā)起請求
這篇文章主要介紹了java web中 HttpClient模擬瀏覽器登錄后發(fā)起請求的相關(guān)資料,需要的朋友可以參考下2017-05-05
SpringBoot Web開發(fā)之系統(tǒng)任務(wù)啟動與路徑映射和框架整合
這篇文章主要介紹了SpringBoot Web開發(fā)中的系統(tǒng)任務(wù)啟動與路徑映射和Servlet、Filter、Listener框架整合,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

