????Welcome Huihui's Code World ! !????
接下來看看由輝輝所寫的關(guān)于xml的相關(guān)操作吧
目錄
????Welcome Huihui's Code World ! !????
是什么
為什么要使用
優(yōu)點
??輝輝小貼士:xml在數(shù)據(jù)庫輔助類中的應(yīng)用
??輝輝小貼士:怎么獲取不同位置下的配置文件呢?
怎么使用
1.DOM4J
代碼示例
2. XPath
代碼示例
3. SAX
4. StAX
5. JAXB
是什么
- XML解析(XML parsing)是指將XML文件中的數(shù)據(jù)解析并轉(zhuǎn)換成計算機程序中可以處理的格式的過程。在XML中,數(shù)據(jù)被存儲為標(biāo)簽和元素的組合,這些標(biāo)簽和元素本質(zhì)上是一些文本字符串。XML解析器(XML parser)可以讀取這些字符串并將它們轉(zhuǎn)換為計算機程序能夠使用的數(shù)據(jù)類型,如字符串、整數(shù)、浮點數(shù)、日期等。通過XML解析,程序可以方便地訪問和操作XML文件中的數(shù)據(jù)。
為什么要使用
優(yōu)點
????????1. 可讀性強
????????????????XML文件使用標(biāo)簽來區(qū)分不同的元素,具有良好的可讀性和可維護(hù)性,有助于開發(fā)人員理解和處理XML文件。
????????2. 結(jié)構(gòu)化數(shù)據(jù)
????????????????XML提供了一種方式來描述數(shù)據(jù)的結(jié)構(gòu)和層次結(jié)構(gòu),有助于開發(fā)人員在處理復(fù)雜數(shù)據(jù)結(jié)構(gòu)時強制執(zhí)行數(shù)據(jù)結(jié)構(gòu)和約束條件。
????????3. 跨平臺和通用性強
????????????????由于XML采用標(biāo)準(zhǔn)化格式,它具有跨平臺和通用性強的優(yōu)勢,可以與不同平臺、不同環(huán)境和不同開發(fā)語言進(jìn)行交互。
????????4. 改善數(shù)據(jù)處理效率
????????????????在大量數(shù)據(jù)需要被處理時,使用XML解析器可以大大提高開發(fā)效率。XML解析器將XML文件解析為對象模型或者樹狀結(jié)構(gòu),可以輕松地對其進(jìn)行訪問、修改和轉(zhuǎn)換,方便了數(shù)據(jù)的處理和管理。
??總之,使用XML解析可以方便地讀取和處理XML文件中的數(shù)據(jù),并提高數(shù)據(jù)處理的效率和可靠性
文字的說服力儼然比不上代碼,那么話不多說,我們直接看代碼
??輝輝小貼士:xml在數(shù)據(jù)庫輔助類中的應(yīng)用
? ? ? ? 下面是我們常寫的數(shù)據(jù)庫輔助類的代碼
????????這樣寫會產(chǎn)生一個問題,那就是會有局限性,如果在后期我的數(shù)據(jù)庫密碼或者是用戶名更改了,那么我就需要將已經(jīng)編譯生成的class文件進(jìn)行反編譯,再次生成java文件之后,對里面的用戶名和密碼進(jìn)行修改,是不是聽起來都特別麻煩?
package com.wh.parse; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * 數(shù)據(jù)庫輔助類 * * @author W * */ public class DBUtils { /** * 加載驅(qū)動 */ static { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("驅(qū)動加載完成????"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 創(chuàng)建連接 * * @return */ public static Connection getcon() { Connection con = null; try { con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=Movie;", "sa", "123"); } catch (Exception e) { e.printStackTrace(); } return con; } /** * 關(guān)閉資源 * * @param con * @param ps * @param rs */ public static void myclose(Connection con, PreparedStatement ps, ResultSet rs) { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (con != null && !con.isClosed()) { con.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(new DBUtils()); } }
那么這時,我們可以將配置文件運用到數(shù)據(jù)庫輔助類中【properties文件】
#oracle9i #driver=oracle.jdbc.driver.OracleDriver #url=jdbc:oracle:thin:@localhost:1521:orcl #user=scott #pwd=*** #sql2005 #driver=com.microsoft.sqlserver.jdbc.SQLServerDriver #url=jdbc:sqlserver://localhost:1433;DatabaseName=test1 #user=sa #pwd=*** #sql2000 #driver=com.microsoft.jdbc.sqlserver.SQLServerDriver #url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB #user=sa #pwd=*** #mysql driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8&useSSL=false user=root pwd=***
可以看到,里面都是需要連接第三方軟件的用戶名,密碼,url...
這樣寫的話,會更加安全,后期修改起來也更為方便
那么我們的DBUtils也會變得更加的方便?。????
package com.wh.parse; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 提供了一組獲得或關(guān)閉數(shù)據(jù)庫對象的方法 * */ public class DBUtils { private static String driver; private static String url; private static String user; private static String password; static {// 靜態(tài)塊執(zhí)行一次,加載 驅(qū)動一次 try { InputStream is = DBUtils.class .getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("pwd"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 獲得數(shù)據(jù)連接對象 * * @return */ public static Connection getConnection() { try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs) { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs) { close(rs); close(stmt); close(conn); } public static boolean isOracle() { return "oracle.jdbc.driver.OracleDriver".equals(driver); } public static boolean isSQLServer() { return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver); } public static boolean isMysql() { return "com.mysql.jdbc.Driver".equals(driver); } public static void main(String[] args) { Connection conn = DBUtils.getConnection(); DBUtils.close(conn); System.out.println("isOracle:" + isOracle()); System.out.println("isSQLServer:" + isSQLServer()); System.out.println("isMysql:" + isMysql()); System.out.println("數(shù)據(jù)庫連接(關(guān)閉)成功"); } }
??輝輝小貼士:怎么獲取不同位置下的配置文件呢?
由于xml的配置文件有多個儲存位置,因此我們也要有相對應(yīng)的獲取不同存放位置下的xml配置文件的方法
首先看一個properties文件
uname=mybatis_ssm upass=xiaoli url=jdbc:mysql://localhost:3306/mybatis_ssm driver_Class=com.mysql.jdbc.Driver initPoolSize=5 maxPoolSize=20
- 配置文件的存放位置
- 同包
InputStream in = Demo1.class.getResourceAsStream("db.properties");//獲取流 Properties p = new Properties();//拿到Properties工具類對象 p.load(in);//加載配置文件內(nèi)容所對應(yīng)的流 System.out.println(p.getProperty("url"));//jdbc:mysql://localhost:3306/mybatis_ssm
- 根目錄? ? ? ?????????
InputStream in = Demo1.class.getResourceAsStream("/db.properties");//獲取流 Properties p = new Properties();//拿到Properties工具類對象 p.load(in);//加載配置文件內(nèi)容所對應(yīng)的流 System.out.println(p.getProperty("url"));// jdbc:mysql://localhost:3306/mybatis_ssm
- 安全路徑【也就是WEB-INF下的位置】
package com.wh.parse; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Properties; @WebServlet("/WebinfServlet") public class WebinfServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream in = request.getServletContext().getResourceAsStream("/WEB-INF/db.properties");//獲取流 Properties p = new Properties();//拿到Properties工具類對象 p.load(in);//加載配置文件內(nèi)容所對應(yīng)的流 System.out.println(p.getProperty("url"));// jdbc:mysql://localhost:3306/mybatis_ssm } }
怎么使用
1.DOM4J
DOM4J是一個開放源代碼的Java庫,是對標(biāo)準(zhǔn)DOM(文檔對象模型)的一種擴(kuò)展。DOM4J提供了靈活的API,使XML文檔的創(chuàng)建、讀取、更新、刪除等操作變得更加易于處理。相較于標(biāo)準(zhǔn)DOM,DOM4j的處理速度更快,內(nèi)存占用較少,而且它的API接口更加簡潔、易于使用,能夠大大提高開發(fā)效率
在 SAXReader 中,獲取 XML 節(jié)點通常使用 Element 類的方法。以下是常用的獲取節(jié)點方法:
?
dom4j中的常用方法 getRootElement()
獲取文檔的根元素 element(String name)
獲取指定名稱的第一個子元素 elements()
獲取所有子元素的迭代器 elements(String name)
獲取指定名稱的所有子元素的迭代器 attribute(String name)
獲取指定名稱的屬性 attributeValue(String name)
獲取指定名稱的屬性的值 getText()
獲取元素的純文本內(nèi)容 getQualifiedName()
獲取元素的限定名(包含命名空間前綴) getName()
獲取元素的名稱(不包含命名空間前綴) getPath()
獲取元素的路徑(包含命名空間前綴) selectNodes(String xpathExpression)
根據(jù) XPath 表達(dá)式獲取所有匹配的節(jié)點列表 selectSingleNode(String xpathExpression)
根據(jù) XPath 表達(dá)式獲取單個匹配的節(jié)點 首先看一個xml文件
uname=mybatis_ssm upass=xiaoli url=jdbc:mysql://localhost:3306/mybatis_ssm driver_Class=com.mysql.jdbc.Driver initPoolSize=5 maxPoolSize=20
代碼示例
package com.wh.parse; import java.io.InputStream; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class Demo2 { /** * 3.怎么學(xué)習(xí)xml的解析 * xml有多個存放位置,我們需要通過相應(yīng)的代碼獲取對應(yīng)位置的xml文件 * 獲取了文件之后,我們有時還需要獲取xml文件的內(nèi)容 * 那么或許文件內(nèi)容有多個方法,我們學(xué)習(xí)的是簡便的方式,提高效率??! * @throws Exception */ public static void main(String[] args) throws Exception { InputStream in =Demo2.class.getResourceAsStream("students.xml");//獲取流 SAXReader sr= new SAXReader(); Document read = sr.read(in);//讀流 // System.out.println(read.asXML());//拿到整個文件的內(nèi)容 List<Element> selectNodes = read.selectNodes("/students/student");//里面放需要拿到對應(yīng)內(nèi)容的node for (Element element : selectNodes) { System.out.println(element.asXML());//拿到所有節(jié)點 Element name = (Element) element.selectSingleNode("name"); System.out.println(name.asXML());//拿到單個節(jié)點 System.out.println(name.getText());//拿到標(biāo)簽中的內(nèi)容 System.out.println(element.attributeValue("sid"));//拿到標(biāo)簽的屬性值 } } }
再來說說DOM4J的主要特點
1. 支持XPath
????????DOM4J支持XPath語法,能夠很方便地遍歷和修改XML文檔中的元素和屬性。
2. 高效性能
????????DOM4J使用快速且內(nèi)存占用較少的觀察者模式訪問XML文檔,能夠在大型XML文檔的處理中達(dá)到更高的性能。
3. 適用于多文檔處理
????????DOM4J支持同時處理多個XML文檔以及并發(fā)操作,能夠高效地處理多種數(shù)據(jù)格式的XML文檔。
4. 支持XML Schema驗證
????????DOM4J支持XML Schema驗證,能夠幫助開發(fā)人員確保XML文檔的有效性和完整性。
5. 提供了多種擴(kuò)展機制
????????DOM4J提供了多種擴(kuò)展機制,如Namespace、ProcessingInstruction、CDATA等,支持對XML文檔進(jìn)行擴(kuò)展處理
2. XPath
????????XPath是一種使用路徑表達(dá)式(類似于文件路徑)在XML文檔中尋找信息的語言,它可以幫助程序員精確定位XML文檔中的節(jié)點。
先看一個xml文件
<?xml version="1.0" encoding="UTF-8"?> <students> <student sid="s001"> <name>小明</name> </student> <student sid="s002"> <name>小芳</name> </student> <student sid='s003'> <name>小王</name> </student> </students>
代碼示例
package com.wh.parse; import java.io.InputStream; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; /** * 用xpath的方式解析xml * @author W * */ public class Demo3 { public static void main(String[] args) throws Exception { InputStream in =Demo2.class.getResourceAsStream("students.xml");//獲取流 SAXReader sr= new SAXReader(); Document read = sr.read(in);//讀流 //拿到students節(jié)點下的student中的id屬性值為s003的name標(biāo)簽的文本并輸出 List<Element> selectNodes = read.selectNodes("/students/student");//里面放需要拿到對應(yīng)內(nèi)容的node for (Element element : selectNodes) { if(element.attributeValue("sid").equals("s003")) { Element name = (Element) element.selectSingleNode("name"); System.out.println(name.getText());//小王 } } //上述代碼太過冗余,接下來讓我們看看更為簡便的xpath解析xml文件 Element element=(Element) read.selectSingleNode("/students/student[@sid='s003']/name"); System.out.println(element.getText());//小王 } }
3. SAX
????????SAX(Simple API for XML)是一種基于事件驅(qū)動的XML解析方式。在SAX解析XML文件時,解析器不需要將整個XML文件讀入內(nèi)存并解析為一個樹形結(jié)構(gòu),而是邊解析邊讀入XML文件,當(dāng)解析器遇到XML文件中的某個節(jié)點時,就觸發(fā)相應(yīng)的事件。
4. StAX
????????StAX(Streaming API for XML)是一種基于拉模型的XML解析方式。StAX解析器將XML文件視為一個流,有兩種模式:事件迭代模式和游標(biāo)模式。在事件迭代模式中,應(yīng)用程序通過調(diào)用解析器提供的next()方法來逐個訪問XML節(jié)點;在游標(biāo)模式中,應(yīng)用程序可以以類似于JDBC結(jié)果集的方式訪問XML節(jié)點。
5. JAXB
????????JAXB(Java Architecture for XML Binding)是一種將XML文檔綁定到Java對象上的方法,它可以將XML文件解析成Java對象,并將Java對象序列化為XML文件。文章來源:http://www.zghlxwxcb.cn/news/detail-499440.html
?? ? ? ? ? ? ?好啦,今天的分享就到這了,希望能夠幫到你呢!????? ? ? ? ? ??????文章來源地址http://www.zghlxwxcb.cn/news/detail-499440.html
到了這里,關(guān)于xml系列篇之xml解析的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!