XML編程總結(四)——使用dom4j方式操作xml,dom4jxml
(四)使用dom4j方式操作xml
dom4j是解析XML的一種開源API,是jdom的升級品,用來讀寫XML文檔。它具有效能優異、功能強大和極易使用的特點,它的效能超過sun公司官方的dom技術。dom4j對Xpath有良好的支援(使用xpath時需要匯入jaxen的jar包),dom4j最大的特色使用大量的介面。使用dom4j時需要匯入dom4j-xxx.jar包。
Attribute ——Attribute定義了XML的屬性
Branch ——Branch為能夠包含子節點的節點如XML元素(Element)和文檔(Docuemnts)定義了一個公用的行為,
CDATA ——CDATA 定義了XML CDATA 地區
CharacterData——CharacterData是一個標識介面,標識基於字元的節點。如CDATA,Comment, Text.
Comment—— Comment 定義了XML注釋的行為
Document—— 定義了XML文檔
DocumentType—— DocumentType 定義XML DOCTYPE聲明
Element—— Element定義XML 元素
ElementHandler ——ElementHandler定義了 Element 對象的處理器
ElementPath 被 ElementHandler 使用,用於取得當前正在處理的路徑層次資訊
Entity ——Entity定義 XML entity
Node ——Node為所有的dom4j中XML節點定義了多態行為
NodeFilter ——NodeFilter 定義了在dom4j節點中產生的一個濾鏡或謂詞的行為(predicate)
ProcessingInstruction ——ProcessingInstruction 定義 XML 處理指示.
Text ——Text 定義XML文本節點.
Visitor—— Visitor 用於實現Visitor模式.
XPath ——XPath 在分析一個字串後會提供一個Xpath運算式
測試類別代碼:
1 public class Dom4jTest { 2 private Document doc; 3 4 @Before 5 public void setUp() throws Exception { 6 // 獲得xml文檔的輸入資料流對象 7 InputStream is = Dom4jTest.class.getClassLoader().getResourceAsStream("books.xml"); 8 // 建立SAXReader對象 9 SAXReader reader = new SAXReader(); 10 // 通過流對象解析xml文檔為Document對象 11 doc = reader.read(is); 12 } 13 14 /** 15 * 使用節點迭代器查詢元素 16 * @throws Exception 17 */ 18 @Test 19 public void testRetrieve() throws Exception { 20 //獲得文檔的根節點 21 Element rootElement = doc.getRootElement(); 22 Iterator iterator = rootElement.elementIterator(); 23 while(iterator.hasNext()){ 24 //獲得子節點,先轉換為Element,有更多的方法 25 Element element = (Element) iterator.next(); 26 String value = element.attributeValue("category"); 27 //獲得屬性為CHILDREN的book節點 28 if("CHILDREN".equals(value)){ 29 //獲得book節點的迭代器 30 Iterator childIterator = element.elementIterator(); 31 while(childIterator.hasNext()){ 32 Node node = (Node) childIterator.next(); 33 //擷取子節點的名稱 34 String name = node.getName(); 35 if("price".equals(name)){ 36 //擷取節點的文本 37 String text = node.getText(); 38 System.out.println(text); 39 } 40 } 41 } 42 } 43 } 44 45 /** 46 * 使用訪問器來讀取xml文檔節點 47 * @throws Exception 48 */ 49 @Test 50 public void testRetrieveByVisitor() throws Exception{ 51 //獲得xml文檔的輸入資料流對象 52 InputStream is = Dom4jTest.class.getClassLoader().getResourceAsStream("books.xml"); 53 // 建立SAXReader對象 54 SAXReader reader = new SAXReader(); 55 // 通過流對象解析xml文檔為Document對象 56 Document doc = reader.read(is); 57 // 獲得文檔的根節點 58 Element rootElement = doc.getRootElement(); 59 //建立自訂的Visitor對象 60 Visitor visitor = new DomVisitor(); 61 //使用visitor查詢文檔 62 rootElement.accept(visitor); 63 } 64 65 /** 66 * 建立新的xml文檔 67 * @throws Exception 68 */ 69 @Test 70 public void testCreate() throws Exception{ 71 //第一種,建立Document的方法(org.dom4j.Document) 72 //第一種建立方式是對第二種建立方式的封裝 73 Document document = DocumentHelper.createDocument(); 74 //第二種,建立Document的方法(org.dom4j.Document) 75 //Document doc = DocumentFactory.getInstance().createDocument(); 76 77 //建立根項目節點 78 Element rootElement = document.addElement("bookstore"); 79 //建立book節點及其子節點 80 Element bookElement = rootElement.addElement("book"); 81 bookElement.addAttribute("CATEGORY", "CODING"); 82 Element title=bookElement.addElement("title"); 83 title.setText("JAVA CODING"); 84 Element author=bookElement.addElement("author"); 85 author.setText("zs"); 86 Element year=bookElement.addElement("year"); 87 year.setText("2010"); 88 Element price=bookElement.addElement("price"); 89 price.setText("69"); 90 //列印到控制台 91 writeToConsole(document); 92 //輸出到檔案 93 writeToFile(document); 94 } 95 96 //輸出到檔案 97 private void writeToFile(Document document) throws IOException { 98 //建立美化格式 99 OutputFormat format=OutputFormat.createPrettyPrint();100 XMLWriter writer=new XMLWriter101 (new FileWriter(new File("abook.xml")),format);102 writer.write(document);103 //關閉writer就會清空緩衝104 writer.close();105 }106 107 //列印到控制台108 private void writeToConsole(Document document) throws IOException {109 //建立輸出字元流110 PrintWriter writer=new PrintWriter(System.out);111 document.write(writer);112 //關閉writer就會清空緩衝,才會輸出來113 writer.close();114 }115 116 /**117 * 使用XPath尋找節點,xpath序號從1開始118 * 要使用dom4j的xpath支援,需要匯入jaxen包119 */120 @Test121 public void testXPath() throws Exception{122 //獲得屬性web的book節點123 Node node = doc.selectSingleNode("//book[@category='WEB']");124 //獲得所有的book節點125 List nodes = doc.selectNodes("//book");126 //獲得第2個book節點127 Node secondNode = doc.selectSingleNode("//book[2]");128 //將xml片段轉換為字串129 String xml = secondNode.asXML();130 System.out.println(xml);131 }132 133 @Test134 public void testStringToXML() throws Exception{135 String xmlString="<book category='CHILDREN'><title lang='en'>Harry Potter</title>"+136 "<author>J K. Rowling</author><year>2005</year><price>29.99</price></book>";137 //轉換字串為xml片段138 Document document = DocumentHelper.parseText(xmlString);139 //列印到控制台140 writeToConsole(document);141 }142 143 /**144 * 刪除指定的節點145 * @throws Exception146 */147 @Test148 public void testDelete() throws Exception{149 //獲得最後一個book節點150 Node node = doc.selectSingleNode("//book[4]");151 //獲得最後一個book節點的父節點152 Element parent = node.getParent();153 //刪除最後一個book節點,刪除需要使用父節點來刪除,刪除成功則返回true154 Boolean flag=parent.remove(node);155 System.out.println(flag);156 //列印到控制台157 writeToConsole(doc);158 }159 160 /**161 * 修改指定的節點162 * @throws Exception163 */164 @Test165 public void testUpdate() throws Exception{166 //獲得第一個book節點的price和year167 Node yearNode = doc.selectSingleNode("//book[1]/year");168 yearNode.setText("2015");169 Node priceNode = doc.selectSingleNode("//book[1]/price");170 priceNode.setText("59.00");171 //修改後的xml文檔列印到控制台172 writeToConsole(doc);173 }174 }
Visitor子類代碼:
1 public class DomVisitor extends VisitorSupport { 2 // 使用棧這個資料結構來儲存 3 private Stack<String> stack = new Stack<String>(); 4 5 // 資料 6 private String attr; 7 private String title; 8 private String author; 9 private String year;10 private double price;11 12 @Override13 public void visit(Document document) {14 }15 16 @Override17 public void visit(Element node) {18 // System.out.println("element node-----------");19 20 //獲得節點的名稱21 String name = node.getName();22 if("book".equals(name)){23 if(!stack.isEmpty()){24 stack.clear();25 }26 stack.push(name);27 }else if("title".equals(node.getName())){28 stack.push(name);29 }else if("author".equals(name)){30 stack.push(name);31 }else if("year".equals(name)){32 stack.push(name);33 }else if("price".equals(name)){34 stack.push(name);35 }36 }37 38 @Override39 public void visit(Attribute node) {40 // System.out.println("attribute node-----");41 42 String peek = stack.peek();43 if("book".equals(peek)){44 String value = node.getValue();45 if("CHILDREN".equals(value)){46 attr=value;47 }48 }49 }50 51 @Override52 public void visit(Text node) {53 // System.out.println("text node--------");54 //注意:一個標籤元素前後都有一個文本節點55 if("CHILDREN".equals(attr)){56 String tag = stack.peek();57 if ("title".equals(tag) && null==title)58 {59 title = node.getText();60 }61 else if ("author".equals(tag) && null==author)62 {63 author = node.getText();64 }65 else if ("year".equals(tag) && null==year)66 {67 year = node.getText();68 }69 else if ("price".equals(tag) && price==0)70 {71 price = Double.parseDouble(node.getText());72 System.out.println(this.toString()); 73 }74 } 75 }76 77 @Override78 public String toString() {79 StringBuilder sb=new StringBuilder();80 sb.append("book attribute:"+attr);81 sb.append("\n");82 sb.append("title:"+title);83 sb.append("\n");84 sb.append("author:"+author);85 sb.append("\n");86 sb.append("year:"+year);87 sb.append("\n");88 sb.append("price:"+price);89 sb.append("\n");90 return sb.toString();91 }92 }
使用Visitor子類讀取文檔結果:
book attribute:CHILDREN
title:Harry Potter
author:J K. Rowling
year:2005