根據一個CRUD的案例,對JAXP解析xml技術,進行詳細的解釋:
首先,已知一個xml文件中的數據如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<書架><書 出版社="深圳出版社1"><!-- 出版社="深圳出版社1"屬性名和屬性值 --><書名>Java</書名><作者>張澤華</作者><售價>39.00元</售價></書><書 出版社="深圳出版社2"><書名>JavaScript網頁開發</書名><作者>李紅蕾</作者><售價>28.00元</售價></書>
</書架>
然后根據單元測試的形式,對CRUD分別寫在一個測試框架方法里面。以方便測試代碼正確性。
package com.itheima.dom;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import junit.framework.Assert;import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;/** * 使用 xml dom 對xml 文件進行 CRUD操作 * 1.讀取節點的文本內容2.讀取屬性值3.添加節點4.刪除節點5.更新節點6.打印所有元素節點的名稱.protected的方法,不讓new對象* */
public class TestDomExercises {// 讀取節點的文本內容 : Java就業培訓教程@Testpublic void testReadContent() throws Exception {// 測試框架異常需要拋出// 獲得代表xml 文件的document 對象Document document = getDocument();// 根據標簽名 獲得 名的標簽的 節點 列表NodeList nl= document.getElementsByTagName("書名");int length = nl.getLength();System.out.println("長度 : " + length);// 返回第一個 書名 節點Node firstBookNameNode = nl.item(0);String result = firstBookNameNode.getTextContent();//String getTextContent() 此屬性返回此節點及其后代的文本內容。 Assert.assertEquals("Java", result);}// 2.讀取屬性值 : 出版社="深圳出版社1"@Testpublic void testReadAttribute() throws Exception {// 獲得document 對象Document document = getDocument();NodeList nl = document.getElementsByTagName("書");// 拿到 第一本書的 節點 對象// Node firstBookNode = nl.item(0);// 注意:這里查看api 之后, 發現Node里面沒有【根據 屬性名獲得屬性值】的方法,而 元素 element 有 直接【根據 屬性名獲得屬性值】的方法, 而這里 拿到的 實際上就是// 一個 元素 Node節點, 所以 這里 想到了強制類型 轉換 , 轉換為 元素Element , 然后 根據他的方法的屬性名獲得屬性的值// 拿到 第一本書//nl.item(0)返回Node對象,向下轉型成Element對象。因為Element里面有直接根據元素找值得方法:getAttribute("出版社");根據名稱獲取屬性的值Element firstBookElement = (Element) nl.item(0);//String getAttribute(String name) 通過名稱獲得屬性值。 String result = firstBookElement.getAttribute("出版社");//根據屬性名獲取屬性值Assert.assertEquals("深圳出版社1", result);}// 3.添加節點 : <售價>79.00元</售價>@Testpublic void testAddPrice() throws Exception, SAXException, IOException {// 獲得document 對象Document document = getDocument();// 獲得第一本書 節點Node firstBookNode = document.getElementsByTagName("書").item(0);// 創建 售價 節點, 并且將 文本設置為 79.00元//Element org.w3c.dom.Document.createElement(String tagName)//Element createElement(String tagName) 創建指定類型的元素。 Element createPriceElement = document.createElement("售價");//createPriceElement.setTextContent("79.00元");//<售價>79.00元</售價>//Node org.w3c.dom.Node.appendChild(Node newChild) firstBookNode.appendChild(createPriceElement);//將節點 newChild 添加到此節點的子節點列表的末尾。如果 newChild 已經存在于樹中,則首先移除它。writeBack2Xml(document);}/** 回去寫代碼時, 如果碰到這個 異常 :* * initializationError(org.junit.runner.manipulation.Filter)* * 就是 你 沒有 加 @Test 注解*/// 4.刪除節點: <售價>39.00元</售價>@Testpublic void testDelete() throws Exception, SAXException, IOException {// 獲得 document 對象Document document = getDocument();// 獲得 售價 39.00元的 節點NodeList priceNodeList = document.getElementsByTagName("售價");for (int i = 0; i < priceNodeList.getLength(); i++) {// 拿到 每個售價節點Node node = priceNodeList.item(i);if ("39.00元".equals(node.getTextContent())) {// 如果進來, 則說明找到 39.00元的售價節點// 拿到當前節點的父節點, 然后 刪除 這個 節點node.getParentNode().removeChild(node);}}// 更新 到 xml 文件writeBack2Xml(document);}// 5.更新節點 : <售價>79.00元</售價> ---------->> <售價>9.9元</售價>public void testUpdatePrice() {}// 6.打印所有元素節點的名稱.@Testpublic void testPrintAllElementsName() throws Exception, SAXException,IOException {// 獲得document 對象Document document = getDocument();printAllElementsName(document);}public void printAllElementsName(Node node) {if (Node.ELEMENT_NODE == node.getNodeType()) {// 說明 就是 元素 節點System.out.println(node.getNodeName());}NodeList childNodes = node.getChildNodes();for (int i = 0; i < childNodes.getLength(); i++) {// 拿到 遍歷過程中的 每一個 nodeNode item = childNodes.item(i);printAllElementsName(item);}}// 需要將內存中的document 對象 重新寫回到 xml 文件中去private void writeBack2Xml(Document document)throws TransformerFactoryConfigurationError,TransformerConfigurationException, TransformerException {// 如何弄?// 查看 文檔, transformerFacotry --->> Transformer實例TransformerFactory factory = TransformerFactory.newInstance();// 獲得轉換器的 實例對象Transformer transformer = factory.newTransformer();// 調用 轉換方法 將 內存中document 對象 寫到 xml 文件中 去//abstract void transform(Source xmlSource, Result outputTarget) 將 XML Source 轉換為 Result。 //DOMSource正好是Source實現類。而且它有構造方法DOMSource(Node n) 正好接收一個Node//Result實現類有一個StreamResult他的構造方法StreamResult.StreamResult(String systemId)
// systemId:Must be a String that conforms to the URI syntax//因此源Source,和結果Result都解決了transformer.transform(new DOMSource(document), new StreamResult("src/book.xml"));}// 抽取 方法 (右鍵——>>refactor--->>rctract method)--->> 重構 -- 抽取 方法private Document getDocument() throws ParserConfigurationException,SAXException, IOException {// 1. 獲得工廠DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 2. 獲得 builder 對象DocumentBuilder builder = factory.newDocumentBuilder();// 3. 拿到 代表xml 文件的document 對象Document document = builder.parse("src/book.xml");return document;}}