Home  >  Article  >  Backend Development  >  Java&Xml Tutorial (4) Using DOM to Generate XML Files

Java&Xml Tutorial (4) Using DOM to Generate XML Files

黄舟
黄舟Original
2017-02-22 14:36:061876browse

In the previous tutorial, we learned to use DOM parsing method to read and modify the content of XML files. Today we will learn how to use DOM parsing mechanism to generate XML files.

The following are our specific requirements for the XML file to be generated:
1. The root node element is "Employees" and the namespace is "http://www.php.cn/" , the root node contains a series of Employee elements.
2. Employee information is represented by the Employee node, and the generated XML file has two pieces of employee information.
3. Each employee has an "id" attribute.
4.The Employee element has four sub-elements - "name", "age", "role", "gender".
The following is the program code:

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;
    }

}

It should be noted that two StreamResult objects are created in the code, one is to output the XML file content to the console for debugging purposes, and the other is to write the XML content into the file.
The XML content output by the program:

<?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>

The XML content is not formatted. If you need to properly format the XML content, refer to this article Formatting XML in Java

In the previous tutorial, we learned to use DOM parsing to read and modify the content of XML files. Today we will learn how to use DOM parsing mechanism to generate XML files.
The following are our specific requirements for the XML file to be generated:
1. The root node element is "Employees", the namespace is "http://www.php.cn/", and the root node contains a Series of Employee elements.
2. Employee information is represented by the Employee node, and the generated XML file has two pieces of employee information.
3. Each employee has an "id" attribute.
4.The Employee element has four sub-elements - "name", "age", "role", "gender".
The following is the program code:

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;
    }

}

It should be noted that two StreamResult objects are created in the code, one is to output the XML file content to the console for debugging purposes, and the other is to write the XML content into the file.
The XML content output by the program:

<?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>

The above is the content of Java&Xml tutorial (4) using DOM method to generate XML files. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn