在前面的教程中,我们学习了使用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内容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees xmlns="http://www.journaldev.com/employee">
<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

Java&Xml教程(四)使用DOM方式生成XML文件的更多相关文章

  1. Java——DOM方式生成XML (转)

    http://blog.csdn.net/u012325167/article/details/50943202 使用DOM方式生成XML文件有如下几步: 首先是创建DOM树(即规定XML文件中的内容 ...

  2. xml常用四种解析方式优缺点的分析×××××

    xml常用四种解析方式优缺点的分析 博客分类: xml   最近用得到xml的解析方式,于是就翻了翻自己的笔记同时从网上查找了资料,自己在前人的基础上总结了下,贴出来大家分享下. 首先介绍一下xml语 ...

  3. 用JAXP的dom方式解析XML文件

    用JAXP的dom方式解析XML文件,实现增删改查操作 dom方式解析XML原理 XML文件 <?xml version="1.0" encoding="UTF-8 ...

  4. 用DOM方式解析XML

    一.用DOM方式解析XML 此例子节点结构如下: 1.获取book节点属性 (1).如果不知道节点的属性,通过 NamedNodeMap attrs = book.getAttributes(); 来 ...

  5. Python中使用dom模块生成XML文件示例

    在Python中解析XML文件也有Dom和Sax两种方式,这里先介绍如何是使用Dom解析XML,这一篇文章是Dom生成XML文件,下一篇文章再继续介绍Dom解析XML文件. 在生成XML文件中,我们主 ...

  6. Dom方式解析XML

    public class TestXML { public static void main(String[] args) throws SAXException, IOException { //D ...

  7. Web.xml中四种验证方式

    源地址:https://blog.csdn.net/imimi_/article/details/78805642 <security-constraint> 的子元素 <http- ...

  8. 在iOS 开发中用GDataXML(DOM方式)解析xml文件

    因为GDataXML的内部实现是通过DOM方式解析的,而在iOS 开发中用DOM方式解析xml文件,这个时候我们需要开启DOM,因为ios 开发中是不会自动开启的,只有在mac 开发中才自动开启的.我 ...

  9. 通俗易懂,C#如何安全、高效地玩转任何种类的内存之Span的脾气秉性(二)。 异步委托 微信小程序支付证书及SSL证书使用 SqlServer无备份下误删数据恢复 把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件中 通过XDocument方式把List写入Xml文件

    通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的脾气秉性(二).   前言 读完上篇<通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的本质(一).>,相信大家对sp ...

随机推荐

  1. codevs1018 单词接龙

    题目描述 Description 单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次), ...

  2. 一个简单的js队列,逻辑很清晰

    function Queue(type) { //type 是否是一个接着一个执行 function QueueConst() {} QueueConst.execute_ing=[], QueueC ...

  3. AWR and ADDM

    The Automatic Workload Repository Oracle collect a vast amount of statistics regarding the performan ...

  4. ISO和焦距

    要说什么是ISO还要从传统胶片相机说起,ISO称作为感光度,它是衡量传统相机所使用胶片感光速度的国际统一指标,其反映了胶片感光时的速度(其实是银元素与光线的光化学反应速率).而对于现在并不使用胶片的数 ...

  5. Node & Express: some tips

    1. 设置Express端口号: 在app.js中添加 app.set('port', process.env.PORT || 3000); 之后命令行中打入 PORT=1234 node app.j ...

  6. 微軟将弃用 System.Data.OracleClient

    http://www.cnblogs.com/WizardWu/archive/2010/05/17/1737009.html 微軟将从 .NET 4 以后的版本弃用 System.Data.Orac ...

  7. C++对象模型——函数的效能(第四章)

    4.3 函数的效能 在以下的这组測试中,在不同的编译器上计算两个3D点,当中用到一个nonmember friend function,一个member function,以及一个 virtual m ...

  8. JAVA高速开发平台 - 开源 免费 - JEECG

    JEECG 微云高速开发平台 当前最新版本号: 3.6.2(公布日期:20160315) 下载地址:http://git.oschina.net/jeecg/jeecg 前言: 随着 WEB UI 框 ...

  9. 【POJ 2777】 Count Color(线段树区间更新与查询)

    [POJ 2777] Count Color(线段树区间更新与查询) Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4094 ...

  10. UVA 11423 - Cache Simulator (树状数组)

    UVA 11423 - Cache Simulator (树状数组) option=com_onlinejudge&Itemid=8&category=523&page=sho ...