XML解析方式分為兩種:dom和sax dom : (DocumentObject Model, 即文件物件模型 ) 是 W3C 組織推薦的解析 XML 的一種方式。 sax : (SimpleAPI for XML) 不是官方標準,但它是 XML 社區事實上的標準,幾乎所有的 XML 解析器都支援它。 XML 解析器:
Crimson ( sun )、 Xerces ( IBM )、 Aelfred2 ( dom4j ) XML 解析開發包: Jaxp (sun) 、 Jdom 、 dom4j 、 pull(android 的 sdk 內建 )
JAXP-DOM: JAXP 是 Sun 提供的一套 XML 解析 API, 很好的支援 DOM 和 SAX 解析方式 JAXP 開發包是 J2SE 的一部分,包括以下包或子包: |--javax.xml
|--org.w3c.dom
|--org.xml.sax 在 javax.xml.parsers 包中,定義了幾個工廠類,程式員調用這些工廠類,可以得到對 xml 文檔進行解析的 DOM 或 SAX 的解析器對象 DOM樹:
使用DOM方式解析XML: 解析器工廠類 DocumentBuilderFactory:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); 解析器類 DocumentBuilder: DocumentBuilder db = dbf.newDocumentBuilder (); 解析產生 Document 對象: Documentdoc = db.parse ("message.xml"); 通過 Document 物件查詢節點: document.getElementById 返回 Node 對象 document.getElementsByTagName 返回 NodeList 對象
節點列表類NodeList: 節點列表類 NodeList 就是代表了一個包含一個或者多個 Node 的列表,可以簡單的把它看成一個 Node 的數組 常用方法 1)getLength():返回列表的長度。 ArrayList size
2)item(int):返回指定位置的Node對象 ArrayList get(index)
節點對象 Node: Node 對象提供了一系列常量來代表結點的類型 當開發人員獲得某個 Node 類型後,就可以把 Node 節點轉換成相應的節點對象 節點的操作: getAttribute (String): 返回標籤中給定屬性的值 ( 元素 ) getAttributeNode (name) :返回指定名稱的屬性節點(元素)
getNodeName () :返回節點的名稱(元素 --> 標籤名) getNodeType () :返回節點的類型 getNodeValue () :返回節點的值
getChildNodes () :返回這個節點的所有子節點列表 getFirstChild () :返回這個節點的第一個子節點
getParentNode () :返回這個節點的父節點對象
appendChild (org.w3c.dom.Node) :為這個節點添加一個子節點,並放在所有子節點的最後,如果這個子節點已經存在,則先把它刪掉再添加進去 removeChild (org.w3c.dom.Node) :刪除給定的子節點對象 replaceChild (org.w3c.dom.Node new , org.w3c.dom.Node old) :用一個新的 Node 對象代替給定的子節點對象
getNextSibling () :返回在 DOM 樹中這個節點的下一個兄弟節點,對等的 getPreviousSibling () 方法返回其前一個兄弟節點 getPreviousSibling () 方法返回其前一個兄弟節點
忽略元素中空白內容:builderFactory.setIgnoringElementContentWhitespace(true);
執行個體:
XML 的 CURD 操作:
CUDTest.java:
<span style="font-size:14px;">package com.example.jaxp.dom;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Source;import javax.xml.transform.Transformer;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;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class CUDTest {public static void main(String[] args) throws Exception {/* * 將內容進行修改:增,刪,改 */// 讀取documentDocument document = CUDTest.getDocument();add(document);update(document);remove(document);}private static void add(Document document) throws Exception {// 增:/* * <book id="b002"> <title>Java in Thinking</title> <price>45</price> * </book> */// 擷取根項目Element rootElement = document.getDocumentElement();// 建立book元素Element newBook = document.createElement("book");// 添加屬性newBook.setAttribute("id", "b003");// 添加元素Element title = document.createElement("title");title.setTextContent("編程思想");newBook.appendChild(title);// 將book元素添加進根項目中rootElement.appendChild(newBook);// 儲存sava(document);}private static void remove(Document document) throws Exception {// 刪:刪除<book id="b001">// 擷取所有的書籍NodeList bookList = document.getElementsByTagName("book");for (int i = 0; i < bookList.getLength(); i++) {// 擷取一本書Node bookNode = bookList.item(i);// 擷取屬性Element bookElement = (Element) bookNode;String id = bookElement.getAttribute("id");// 判斷idif (id.equals("b001")) {// 擷取父節點Node parent = bookElement.getParentNode();// 從父節點刪除子節點parent.removeChild(bookElement);}}// 儲存sava(document);}private static void update(Document document) throws Exception {// 修改:修改<price>22</price> 為35// 擷取所有的書籍NodeList bookList = document.getElementsByTagName("book");for (int i = 0; i < bookList.getLength(); i++) {// 擷取一本書Node bookNode = bookList.item(i);// 擷取屬性Element bookElement = (Element) bookNode;String id = bookElement.getAttribute("id");// 判斷idif (id.equals("b001")) {// 擷取所有的titleNodeList priceList = bookElement.getElementsByTagName("price");// 擷取唯一的titleNode price = priceList.item(0);// 修改:price.setTextContent("35");}}// 儲存sava(document);}private static void sava(Document document) throws Exception {//儲存// 擷取持久化對象工廠執行個體TransformerFactory factory = TransformerFactory.newInstance();// 擷取持久化Transformer transformer = factory.newTransformer();// 源:Source xmlSource = new DOMSource(document);// 結果:StreamResult outputTarget = new StreamResult("Book.jasp.xml");transformer.transform(xmlSource, outputTarget);System.out.println("done");}public static Document getDocument() throws Exception {//讀// 擷取解析器工廠執行個體DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 擷取解析器DocumentBuilder builder = factory.newDocumentBuilder();// 擷取documentDocument document = builder.parse("Book.xml");return document;}}</span>
(讀取)DomTest.java:
<span style="font-size:14px;">package com.example.jaxp.dom;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.example.domain.Book;public class DomTest {public static void main(String[] args) throws Exception {System.out.println(getAllBooks());}/* * 獲得所有的書籍,將所有的書籍內容儲存list */public static List<Book> getAllBooks() throws Exception {String title = "";String price = "";//建立list,用於儲存所有的資料List<Book> bookList = new ArrayList<Book>();/* * 從xml文檔中將需求的資料,查詢出來,替換類比資料 */// 獲得工廠執行個體DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 獲得解析器DocumentBuilder builder = factory.newDocumentBuilder();// 獲得document ----解析xml檔案 路徑問題會導致:java.io.FileNotFoundExceptionDocument document = builder.parse("Book.xml");// 擷取元素NodeList bookElements = document.getElementsByTagName("book");// 遍曆所有的書籍元素,擷取元素屬性for (int i = 0; i < bookElements.getLength(); i++) {Node node = bookElements.item(i);// 父類給子類Element bookEle = (Element) node;// 擷取 元素屬性 idString id = bookEle.getAttribute("id");//System.out.println(id);// 查詢title和price// 擷取當前節點(book元素)的所有子節點NodeList childList = bookEle.getChildNodes();// 遍曆子節點for (int c = 0; c < childList.getLength(); c++) {// 擷取所有的孩子Node childNode = childList.item(c);String childName = childNode.getNodeName();// 判斷標籤是否是titleif ("title".equals(childName)) {// 擷取title內容title = childNode.getTextContent();} else if ("price".equals(childName)) {// 擷取price內容price = childNode.getTextContent();}}// 建立Javabean對象Book book = new Book();book.setId(id);book.setTitle(title);book.setPrice(price);bookList.add(book);}return bookList;}}</span>