Java&Xml教程(四)使用DOM方式生成XML文件

在前面的教程中,我们学习了使用DOM解析方式读取和修改XML文件内容,今天我们来学习如何使用DOM解析机制生成XML文件。
下面是我们对要生成的XML文件的具体要求:
1.根节点元素为”Employees”,命名空间为”http://www.journaldev.com/employee“,根节点下包含一系列的Employee元素。
2.员工的信息通过Employee节点表示,生成的XML文件有两条员工的信息。
3.每个员工有个”id”属性。
4.Employee 元素有四个子元素- “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;
    }

}

需要注意的是代码中创建了两个StreamResult对象,一个是出于调试的目的將XML文件内容输出到控制台中,另一个將XML内容写到文件中。
程序输出的XML内容:


<Employees xmlns="http://www.journaldev.com/employee">
<Employee id="1">
<name>Pankajname>
<age>29age>
<role>Java Developerrole>
<gender>Malegender>
Employee>
<Employee id="2">
<name>Lisaname>
<age>35age>
<role>Managerrole>
<gender>Femalegender>
Employee>
Employees>

该XML内容没有格式化,如果你需要对XML内容做适当的格式化,参考这篇文章Java中格式化XML

转载于:https://www.cnblogs.com/lanzhi/p/6468393.html

你可能感兴趣的:(Java&Xml教程(四)使用DOM方式生成XML文件)