1. 程式人生 > >dom4j組裝xml 以及解析xml

dom4j組裝xml 以及解析xml

next des pan count() entry col shu ron 一行

dom4j組裝xml 以及解析xml:

1.下載dom4j的jar包,地址:https://dom4j.github.io/

2.java代碼:

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import
javax.xml.parsers.ParserConfigurationException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.xml.sax.SAXException;
/** * dom4j解析xml * @author lyc * */ public class DOM4J { public static void main(String[] args) { DOM4J dom4j= new DOM4J(); try { dom4j.objectToXml(); //dom4j.xmlToObject(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// 獲取並解析xml格式文件為object public void xmlToObject() throws ParserConfigurationException, DocumentException, SAXException, IOException{ SAXReader saxReader = new SAXReader(); //將獲取的xml 轉化為document 文檔 //這裏使用了File當然也可以使用URL()從指定url獲取xml並進行解析 Document document = saxReader.read(new File("src/1.xml")); // 獲取根元素 Element root = document.getRootElement(); // 根元素名稱 System.out.println("reservationList Root----: " + root.getName()); // 獲取所有子元素 List<Element> childList = root.elements(); System.out.println("total reservation child count: " + childList.size()); System.out.println("第一個reservation的quotationId節點值:"+childList.get(0).element("quotationId").getTextTrim()); for(Element e : childList){ /*Element helloElement = e.element("quotationId"); System.out.println(helloElement.getTextTrim());*/ Element insurantListE = e.element("insurantList"); List<Element> insurantList = insurantListE.elements(); System.out.println("total insurant child count: " + insurantList.size()); for(Element e1 : insurantList){ Element helloElement1 = e1.element("insurantName"); System.out.println(helloElement1.getTextTrim()); } } /*// 獲取特定名稱的子元素 List<Element> childList2 = root.elements("reservation"); Element helloElement = root.element("quotationId"); System.out.println("hello child: " + childList2.size()); // 獲取特定名稱的子元素的值 System.out.println("hello----"+childList2.get(0).getText()); System.out.println("hello----"+helloElement.getText().trim()); System.out.println("叠代輸出-----------------------");*/ // 叠代輸出 /*for (Iterator iter = root.elementIterator(); iter.hasNext();) { // 獲取根目錄下的元素 Element e = (Element) iter.next(); // 獲取元素對應的值 System.out.println(e.getText()); // 元素的屬性個數 System.out.println(e.attributeCount()); //獲取元素的第一個屬性的名稱 System.out.println(e.attribute(0).getName()); //獲取元素的第一個屬性的值 System.out.println(e.attribute(0).getValue()); //獲取元素的第二個屬性的名稱 System.out.println(e.attribute(1).getName()); //獲取元素的第二個屬性的值 System.out.println(e.attribute(1).getValue()); //按照屬性名稱獲取屬性值 System.out.println("are you ok :"+e.attributeValue("age")); System.out.println("are you ok :"+e.attributeValue("name")); }*/ // 使用DOMReader將xml轉化為object /*System.out.println("用DOMReader-----------------------"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // 註意要用完整類名 //將獲取的xml 轉化為document 文檔 org.w3c.dom.Document document2 = db.parse(new File("F:/student2.xml")); DOMReader domReader = new DOMReader(); // 將JAXP的Document轉換為dom4j的Document Document document3 = domReader.read(document2); Element rootElement = document3.getRootElement(); System.out.println("Root: " + rootElement.getName());*/ } // 將對象組裝成xml格式文件並保存 public void objectToXml ()throws Exception{ // 第一種方式:創建文檔,並創建根元素 // 創建文檔:使用了一個Helper類 Document document = DocumentHelper.createDocument(); // 創建根節點並添加進文檔 Element root = DocumentHelper.createElement("student"); document.setRootElement(root); // 第二種方式:創建文檔並設置文檔的根元素節點 Element root2 = DocumentHelper.createElement("student"); Document document2 = DocumentHelper.createDocument(root2); // 給元素添加屬性 root2.addAttribute("name", "zhangsan"); Element e = root2.addElement("courses"); /*Map<String,Object> map1 = new HashMap<String,Object>(); Map<String,Object> map2 = new HashMap<String,Object>(); List<Map<String,Object>> list = new ArrayList(); map2.put("yuwen", "語文"); map2.put("shuxue", "數學"); list.add(map1); list.add(map2);*/ /*for(Map map : list){ Element courseElement = e.addElement(map.entrySet().iterator().next().toString()); courseElement.setText(map.get(map.entrySet().iterator().next().toString()).toString()); }*/ Element yuwenElement = e.addElement("yuwen"); Element shuxueElement = e.addElement("shuxue"); yuwenElement.setText("語文"); shuxueElement.setText("數學"); /* // 添加子節點:add之後就返回這個元素 Element helloElement = root2.addElement("hello"); Element worldElement = root2.addElement("world"); //給元素添加屬性key-value worldElement.addAttribute("age","12"); worldElement.addAttribute("name","www"); helloElement.addAttribute("age","13"); helloElement.addAttribute("name","wws"); //元素的節點的值 helloElement.setText("hello Text"); worldElement.setText("world text");*/ // 輸出 // 輸出到控制臺 XMLWriter xmlWriter = new XMLWriter(); xmlWriter.write(document); //輸出到文件 //其中的" "表示格式,true參數表示另起一行,gb2312表示編碼,如果不寫這個參數則默認utf-8編碼 //1、OutputFormat format=new OutputFormat(" ",true,"gb2312"); //生成壓縮格式、緊湊格式的xml 其中的compactFormat 翻譯:壓縮格式 //2、 OutputFormat format = OutputFormat.createCompactFormat(); //調用靜態方法創建一個沒有格式的打印方式 //3、 OutputFormat format = OutputFormat.createPrettyPrint(); //format.setEncoding("gb2312"); // 設置編碼 OutputFormat format = new OutputFormat(" ", true);// 設置縮進為2個空格,並且另起一行為true XMLWriter xmlWriter2 = new XMLWriter( new FileOutputStream("C:/Users/lyc/Desktop/student1.xml"), format); xmlWriter2.write(document2); xmlWriter2.flush(); xmlWriter2.close(); // 另一種輸出方式,記得要調用flush()方法,否則輸出的文件中顯示空白,調用close() 方法釋放資源 XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("C:/Users/lyc/Desktop/student2.xml"), format); xmlWriter3.write(document2); xmlWriter3.flush(); xmlWriter3.close(); } }

3.需要解析的xml內容:
1.xml:(自己定義xml文件),例如:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan">
  <courses>
    <yuwen>語文</yuwen>
    <shuxue>數學</shuxue>
  </courses>
</student>

4.生成xml文件:

student1.xml:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan">
  <courses>
    <yuwen>語文</yuwen>
    <shuxue>數學</shuxue>
  </courses>
</student>

student2.xml:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan">
  <courses>
    <yuwen>語文</yuwen>
    <shuxue>數學</shuxue>
  </courses>
</student>

dom4j組裝xml 以及解析xml