在前面的教程中,我们学习了使用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. ceph rbd 入门

    1.一个现成的ceph cluster 参考之前写的ceph-deploy 部署ceph cluster 2.配置client与ceph cluster对接 在ceph cluster的管理节点上安装 ...

  2. TensorFlow Ops

    TensorFlow Ops 1. Fun with TensorBoard In TensorFlow, you collectively call constants, variables, op ...

  3. Wow! Such Sequence! (线段树) hdu4893

    http://acm.hdu.edu.cn/showproblem.php?pid=4893 先贴上一份还没过的代码,不知道拿出错了  1 // by caonima ; ; ],col[MAX< ...

  4. hdu 2094拓扑排序map实现记录

    #include<stdio.h> #include<iostream> #include<algorithm> #include<string> #i ...

  5. Ubuntu下使用Sysvinit实现自定义服务(简单研究)

    通过上一篇文章http://www.cnblogs.com/EasonJim/p/7168216.html可以大概了解到Sysvinit的历史. 其实在自定义服务上,使用Sysvinit是最简单的,本 ...

  6. 26、Java并发性和多线程-线程池

    以下内容转自http://ifeve.com/thread-pools/: 线程池(Thread Pool)对于限制应用程序中同一时刻运行的线程数很有用.因为每启动一个新线程都会有相应的性能开销,每个 ...

  7. 可恢复的安全rm

    我们常常使用rm去删除一些文件.假设不小手一抖,那么就悲剧了.你们都懂的... 在经历过一次这种慘剧后.决定永远杜绝这种情况.重写写了shell函数.运行安全的rm.这个函数会把要删除的文件按日期备份 ...

  8. ganglia收集hbase的metrics

    Ganglia 是 UC Berkeley 发起的一个开源监视项目,设计用于測量数以千计的节点.每台计算机都执行一个收集和发送度量数据(如处理器速度.内存使用量等)的名为 gmond 的守护进程.它将 ...

  9. [C]if (CONDITION)语句中CONDITION的情况

    编译环境: Ubuntu 12.04: gcc Windows XP : VS-2005 深入一下if (CONDITION)语句中CONDITION的情况.即CONDITION何时为真,何时是假. ...

  10. C语言strdup()函数:复制字符串【转】

    本文转载自:http://c.biancheng.net/cpp/html/166.html 头文件:#include <string.h> 定义函数:char * strdup(cons ...