java中對xml的讀取和寫入
阿新 • • 發佈:2018-12-16
java對xml操作需匯入dom4j的jar包(如下):
(解析)讀取xml:
package com.rj.bd.xml.jx; import java.io.File; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * @desc 解析xml檔案 * @author ws * @time 2018-10-9 */ public class LianXi01 { public static void main(String[] args) throws DocumentException { String pathname = "E:/xml/ren.xml"; File file = new File(pathname); if (file.isFile() && file.exists()) { System.out.println("檔案存在"); //獲取文件 SAXReader reader = new SAXReader(); Document document = reader.read(file); System.out.println(document.asXML());//輸出document //獲取根元素 Element rootE = document.getRootElement(); System.out.println("根元素名稱:"+rootE.getName());//輸出根元素名字 //獲取根元素屬性 List<Attribute> rootA = rootE.attributes();//根元素屬性存list並指定泛型為dom4j的Attribute介面 for (Attribute eveRootA : rootA) { System.out.println("根元素屬性:"+eveRootA.getName()+"\t"+eveRootA.getValue());//輸出根元素屬性的屬性名和屬性值 } //獲取根元素的子元素 List<Element> ziE = rootE.elements();//指定泛型為Element for (Element eveZiE : ziE) { System.out.println("子元素名稱:"+eveZiE.getName()); List<Attribute> ziA = eveZiE.attributes(); for (Attribute eveZiA : ziA) { System.out.println("子元素屬性:"+eveZiA.getName()+"\t"+eveZiA.getValue()); } //獲取子元素中的子元素 List<Element> ziZiE = eveZiE.elements(); for (Element eveZiZiE : ziZiE) { System.out.println("子元素的子元素的名稱和文字值:"+eveZiZiE.getName()+"\t"+eveZiZiE.getText()); List<Attribute> ziZiA = eveZiZiE.attributes(); for (Attribute eveZiZiA : ziZiA) { System.out.println("子元素的子元素的屬性:"+eveZiZiA.getName()+"\t"+eveZiZiA.getValue()); } } } } } }
寫入xml:
package com.rj.bd.xml.xr; import java.io.FileWriter; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * @desc xml的寫入 * @author ws * @time 2018-10-9 */ public class LianXi01 { public static void main(String[] args) throws IOException { //建立一個document物件 Document document = DocumentHelper.createDocument(); //加入根元素 Element rootE = document.addElement("people"); //加入根元素屬性 rootE.addAttribute("name", "Lily"); rootE.addAttribute("sex", "Women"); //加入子元素 Element zuoYan = rootE.addElement("eyes"); Element youYan = rootE.addElement("eyes"); //子元素加屬性和文字值 zuoYan.addAttribute("num", "0.5"); zuoYan.addText("左眼"); youYan.addAttribute("num", "0.5"); youYan.addText("右眼"); //設定格式化輸出標準 OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8");//設定編碼格式 format.setIndent(" ");//設定首行縮排 format.setNewlines(true);//設定換行 //寫入 String path = "E:/xml/people.xml"; FileWriter write = new FileWriter(path); XMLWriter xmlWriter = new XMLWriter(write,format); xmlWriter.write(document);//寫入文件 System.out.println("寫入成功!"); //關閉流物件 xmlWriter.close(); write.close(); } }