溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用DOM方式生成XML文件

發(fā)布時(shí)間:2020-07-09 14:03:25 來(lái)源:億速云 閱讀:173 作者:Leah 欄目:編程語(yǔ)言

如何使用DOM方式生成XML文件?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

下面是我們對(duì)要生成的XML文件的具體要求:
1.根節(jié)點(diǎn)元素為”Employees”,命名空間為”http://www.php.cn/“,根節(jié)點(diǎn)下包含一系列的Employee元素。
2.員工的信息通過(guò)Employee節(jié)點(diǎn)表示,生成的XML文件有兩條員工的信息。
3.每個(gè)員工有個(gè)”id”屬性。
4.Employee 元素有四個(gè)子元素- “name”, “age”, “role”, “gender”。
下面是程序代碼:

package com.journaldev.xml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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;
public class XMLWriterDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            //add elements to Document
            Element rootElement =
                doc.createElementNS("http://www.journaldev.com/employee", "Employees");
            //append root element to document
            doc.appendChild(rootElement);

            //append first child element to root element
            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));

            //append second child
            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));

            //for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            //write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));

            //write data
            transformer.transform(source, console);
            transformer.transform(source, file);
            System.out.println("DONE");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static Node getEmployee(Document doc, String id, String name, String age, String role,
            String gender) {
        Element employee = doc.createElement("Employee");

        //set id attribute
        employee.setAttribute("id", id);

        //create name element
        employee.appendChild(getEmployeeElements(doc, employee, "name", name));

        //create age element
        employee.appendChild(getEmployeeElements(doc, employee, "age", age));

        //create role element
        employee.appendChild(getEmployeeElements(doc, employee, "role", role));

        //create gender element
        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));

        return employee;
    }


    //utility method to create text node
    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }

}

需要注意的是代碼中創(chuàng)建了兩個(gè)StreamResult對(duì)象,一個(gè)是出于調(diào)試的目的將XML文件內(nèi)容輸出到控制臺(tái)中,另一個(gè)將XML內(nèi)容寫到文件中。
程序輸出的XML內(nèi)容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees xmlns=" 
<Employee id="1"><name>Pankaj</name><age>29</age><role>Java Developer</role><gender>Male</gender></Employee>
<Employee id="2"><name>Lisa</name><age>35</age><role>Manager</role><gender>Female</gender></Employee></Employees>

該XML內(nèi)容沒(méi)有格式化,如果你需要對(duì)XML內(nèi)容做適當(dāng)?shù)母袷交瑓⒖歼@篇文章Java中格式化XML

在前面的教程中,我們學(xué)習(xí)了使用DOM解析方式讀取和修改XML文件內(nèi)容,今天我們來(lái)學(xué)習(xí)如何使用DOM解析機(jī)制生成XML文件。
下面是我們對(duì)要生成的XML文件的具體要求:
1.根節(jié)點(diǎn)元素為”Employees”,命名空間為”http://www.php.cn/“,根節(jié)點(diǎn)下包含一系列的Employee元素。
2.員工的信息通過(guò)Employee節(jié)點(diǎn)表示,生成的XML文件有兩條員工的信息。
3.每個(gè)員工有個(gè)”id”屬性。
4.Employee 元素有四個(gè)子元素- “name”, “age”, “role”, “gender”。
下面是程序代碼:

package com.journaldev.xml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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;
public class XMLWriterDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            //add elements to Document
            Element rootElement =
                doc.createElementNS("http://www.journaldev.com/employee", "Employees");
            //append root element to document
            doc.appendChild(rootElement);

            //append first child element to root element
            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));

            //append second child
            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));

            //for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            //write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));

            //write data
            transformer.transform(source, console);
            transformer.transform(source, file);
            System.out.println("DONE");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static Node getEmployee(Document doc, String id, String name, String age, String role,
            String gender) {
        Element employee = doc.createElement("Employee");

        //set id attribute
        employee.setAttribute("id", id);

        //create name element
        employee.appendChild(getEmployeeElements(doc, employee, "name", name));

        //create age element
        employee.appendChild(getEmployeeElements(doc, employee, "age", age));

        //create role element
        employee.appendChild(getEmployeeElements(doc, employee, "role", role));

        //create gender element
        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));

        return employee;
    }


    //utility method to create text node
    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }

}

需要注意的是代碼中創(chuàng)建了兩個(gè)StreamResult對(duì)象,一個(gè)是出于調(diào)試的目的將XML文件內(nèi)容輸出到控制臺(tái)中,另一個(gè)將XML內(nèi)容寫到文件中。
程序輸出的XML內(nèi)容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees xmlns=" 
<Employee id="1"><name>Pankaj</name><age>29</age><role>Java Developer</role><gender>Male</gender></Employee>
<Employee id="2"><name>Lisa</name><age>35</age><role>Manager</role><gender>Female</gender></Employee></Employees>

關(guān)于如何使用DOM方式生成XML文件問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI