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

黄舟
풀어 주다: 2017-02-22 14:36:06
원래의
1852명이 탐색했습니다.

在前面的教程中,我们学习了使用DOM解析方式读取和修改XML文件内容,今天我们来学习如何使用DOM解析机制生成XML文件。 

下面是我们对要生成的XML文件的具体要求:
1.根节点元素为”Employees”,命名空间为”//m.sbmmt.com/“,根节点下包含一系列的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内容:

<?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内容没有格式化,如果你需要对XML内容做适当的格式化,参考这篇文章Java中格式化XML

在前面的教程中,我们学习了使用DOM解析方式读取和修改XML文件内容,今天我们来学习如何使用DOM解析机制生成XML文件。
下面是我们对要生成的XML文件的具体要求:
1.根节点元素为”Employees”,命名空间为”//m.sbmmt.com/“,根节点下包含一系列的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内容:

<?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>
로그인 후 복사

以上就是Java&Xml教程(四)使用DOM方式生成XML文件的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!