1. 程式人生 > >DOM物件對xml檔案的讀取和寫入

DOM物件對xml檔案的讀取和寫入

解析的XML檔案對應的java類

package com.nm;

public class Employee {

    private String eid;
    private String name;
    private String gender;
    private int age;
    private String address;
    @Override
    public String toString() {
        return "Employee [eid=" + eid + ", name=" + name + ", gender="
+ gender + ", age=" + age + ", address=" + address + "]"; } public String getEid() { return eid; } public void setEid(String eid) { this.eid = eid; } public String getName() { return name; } public void setName(String name) { this
.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress
() { return address; } public void setAddress(String address) { this.address = address; } public Employee(String eid, String name, String gender, int age, String address) { super(); this.eid = eid; this.name = name; this.gender = gender; this.age = age; this.address = address; } public Employee() { super(); // TODO Auto-generated constructor stub } }

操作XML檔案的TestXml類

package com.nm;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

public class TestXml {

    /***
     * 讀取xml檔案
     * @param fileName
     * @return employees
     * @throws Exception
     */
    public static List<Employee> readXMLFile(String fileName) 
            throws Exception{
        //得到dom解析器的工廠例項
        DocumentBuilderFactory dbf = 
                DocumentBuilderFactory.newInstance();
        DocumentBuilder bulid = null;
        try{
            //從dom工廠物件獲取dom解析器
            bulid = dbf.newDocumentBuilder();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }

        Document doc = null;
        try{
            //解析xml文件的document物件
            doc = bulid.parse(fileName);
            //去掉xml文件中格式化內容空白
            doc.normalize();
        }catch(Exception dom){
            dom.printStackTrace();  
        }

        //建立employee的集合
        List<Employee> employees = 
                new ArrayList<Employee>();
        //建立employee物件
        Employee employee = null;
        //獲取xml文件的根節點
        Element root = doc.getDocumentElement();
        //獲取xml文件employee元素節點集合
        NodeList nodeList = 
                root.getElementsByTagName("employee");
        //遍歷employee元素下的節點
        for(int i=0;i<nodeList.getLength();i++){
            //依次獲取每個employee元素
            Element element = (Element) nodeList.item(i);
            //建立一個員工物件
            employee = new Employee();
            //給員工的編號屬性賦值
            employee.setEid(element.getAttribute("id"));
            //給員工的性別屬性賦值
            employee.setGender(element.getAttribute("gender"));
            //取員工名字元素
            NodeList name = element.getElementsByTagName("name");
            if(name.getLength() == 1){
                Element e = (Element) name.item(0);
                //取名字元素的第一個子節點,就是名字的值節點
                Text t = (Text) e.getFirstChild();
                //給員工的姓名屬性賦值
                employee.setName(t.getNodeValue());
            }
            //取員工年齡元素
            NodeList age = element.getElementsByTagName("age");
            if(age.getLength() == 1){
                Element e = (Element) age.item(0);
                //取年齡元素的第一個子節點,就是年齡的值節點
                Text t = (Text) e.getFirstChild();
                //給員工的年齡屬性賦值
                employee.setAge(Integer.parseInt(t.getNodeValue()));
            }
            //取員工地址元素
            NodeList address = element.getElementsByTagName("address");
            if(address.getLength() == 1){
                Element e = (Element) address.item(0);
                //取地址元素的第一個子節點,就是地址的值節點
                Text t = (Text) e.getFirstChild();
                //給員工的地址屬性賦值
                employee.setAddress(t.getNodeValue());
            }
            //將employee塞入list集合中
            employees.add(employee);
        }
        return employees;
    }

    /***
     * 用dom寫xml文件,把員工資訊以xml文件的形式儲存
     * @param outFile
     * @param employees
     * @return domDocToFile(doc, outFile, outFile)
     * @throws Exception
     */
    public static String wirteXMLFile(String outFile,List<Employee> employees) 
            throws Exception{
        //得到dom解析器的工廠例項
        DocumentBuilderFactory dbf = 
                DocumentBuilderFactory.newInstance();
        DocumentBuilder bulid = null;
        try{
            //從dom工廠物件獲取dom解析器
            bulid = dbf.newDocumentBuilder();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
        //新建一個空白文件
        Document doc = bulid.newDocument();
        //建立根元素employees
        Element root = doc.createElement("employees");
        //將根節點新增進入文件
        doc.appendChild(root);
        //迴圈獲取員工的資訊
        for(int i=0;i<employees.size();i++){
            //依次獲取員工的資訊
            Employee emp = employees.get(i);
            //建立employee元素,有編號和性別屬性
            Element element = doc.createElement("employee");
            //設定編號和性別
            element.setAttribute("id", emp.getEid());
            element.setAttribute("gender", emp.getGender());
            root.appendChild(element);
            //建立name元素
            Element name = doc.createElement("name");
            //將name元素新增如employee元素下
            element.appendChild(name);
            //往name元素中屬性賦值
            Text tname = doc.createTextNode(emp.getName());
            //將屬性值新增如name元素中
            name.appendChild(tname);
            //建立age元素
            Element age = doc.createElement("age");
            //將age元素新增如employee元素下
            element.appendChild(age);
            //往age元素中屬性賦值
            Text tage = doc.createTextNode(""+emp.getAge());
            //將屬性值新增如age元素中
            name.appendChild(tage);
            //建立address元素
            Element address = doc.createElement("address");
            //將age元素新增如employee元素下
            element.appendChild(address);
            //往age元素中屬性賦值
            Text taddress = doc.createTextNode(""+emp.getAddress());
            //將屬性值新增如age元素中
            name.appendChild(taddress); 
        }
        return domDocToFile(doc, outFile, outFile);

    }

    /***
     * 使用jaxp將dom物件寫入xml文件中
     * @param doc
     * @param fileName
     * @param encoding
     * @return file.getAbsolutePath()
     * @throws TransformerException
     */
    public static String domDocToFile(Document doc,String fileName,String encoding)
        throws TransformerException{
        //為了得到xslt引擎建立物件
        TransformerFactory tff = 
                TransformerFactory.newInstance();
        //建立xslt引擎物件輸出xml文件
        Transformer tf = tff.newTransformer();
        //獲取屬性物件
        Properties pro = tf.getOutputProperties();
        //設定編碼格式和輸出格式
        pro.setProperty(OutputKeys.ENCODING, encoding);
        pro.setProperty(OutputKeys.METHOD, "xml");
        tf.setOutputProperties(pro);
        //建立資源物件
        DOMSource source = new DOMSource(doc);
        //建立檔案物件
        File file = new File(fileName);

        //獲得輸出物件
        StreamResult result = new StreamResult(file);
        //結果輸出到控制檯
        StreamResult result1 = new StreamResult(System.out);
        //執行dom文件到xml檔案轉換
        tf.transform(source, result);
        //文件輸出到控制檯
        tf.transform(source, result1);
        System.out.println();
        //將輸出檔案的路徑返回
        return file.getAbsolutePath();
    }

    public static void main(String[] args) {
        String in = "H:test.xml";
        String out = "H:test1.xml";
        try{
            List<Employee> emps = TestXml.readXMLFile(in);
            System.out.println("輸出到控制檯的xml文件:");
            System.out.println("檔案(包括路徑和字尾):"+TestXml.wirteXMLFile(out, emps));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}