Java 操纵XML之创建XML文件

一、JAVA DOM PARSER

DOM interfaces
  The DOM defines several Java interfaces. Here are the most common interfaces:
    Node - The base datatype of the DOM.
    Element - The vast majority of the objects you'll deal with are Elements.
    Attr Represents an attribute of an element.
    Text The actual content of an Element or Attr.
    Document Represents the entire XML document. A Document object is often referred to as a DOM tree.
Common DOM methods
  When you are working with the DOM, there are several methods you'll use often:
    Document.getDocumentElement() - Returns the root element of the document.
    Node.getFirstChild() - Returns the first child of a given Node.
    Node.getLastChild() - Returns the last child of a given Node.
    Node.getNextSibling() - These methods return the next sibling of a given Node.
    Node.getPreviousSibling() - These methods return the previous sibling of a given Node.
    Node.getAttribute(attrName) - For a given Node, returns the attribute with the requested name.

二、源代码:CreateXmlFile.java

 package cn.com.zfc.lesson26.xml;

 import java.io.File;

 import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text; /**
* 使用JAVA DOM PARSER:创建 XML 文件
*
* @author zfc
* @date 2017年12月7日 下午6:11:27
*/
public class CreateXmlFile {
public static void main(String[] args) { try {
// 1、创建 DocumentBuilderFactory 对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// 2、创建 DocumentBuilder 对象
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// 3、创建 Document 对象
Document document = documentBuilder.newDocument();
// 4、创建元素,创建一个根元素
Element students = document.createElement("students");
// 5、将根元素添加到文档对象中
document.appendChild(students); // 6、创建第一个学生
Element student = document.createElement("student");
// 创建一个属性对象
Attr attr = document.createAttribute("id");
// 给属性设值
attr.setValue("student1");
// 将属性添加到 student 结点上
student.setAttributeNode(attr);
// 创建 name 子结点
Element name = document.createElement("name");
// 创建文本结点
Text nameValue = document.createTextNode("Tom");
// 将文本结点添加到 name 结点上
name.appendChild(nameValue);
// 将 name 结点添加到 student 结点上
student.appendChild(name);
// 创建 sex 结点
Element sex = document.createElement("sex");
// 创建 文本结点
Text sexValue = document.createTextNode("Female");
// 将 sexValue 添加到 sex 结点上
sex.appendChild(sexValue);
// 将 sex 结点添加到 student 结点上
student.appendChild(sex);
// 将 student 结点添加到 students 结点中
students.appendChild(student); // 7、添加第二个学生
student = document.createElement("student");
// 创建一个属性对象
attr = document.createAttribute("id");
// 给属性设值
attr.setValue("student2");
// 将属性添加到 student 结点上
student.setAttributeNode(attr);
// 创建 name 子结点
name = document.createElement("name");
// 创建文本结点
nameValue = document.createTextNode("Lucy");
// 将文本结点添加到 name 结点上
name.appendChild(nameValue);
// 将 name 结点添加到 student 结点上
student.appendChild(name);
// 创建 sex 结点
sex = document.createElement("sex");
// 创建 文本结点
sexValue = document.createTextNode("Male");
// 将 sexValue 添加到 sex 结点上
sex.appendChild(sexValue);
// 将 sex 结点添加到 student 结点上
student.appendChild(sex);
// 将 student 结点添加到 students 结点中
students.appendChild(student); // 8、创建 TransformerFactory 对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// 9、创建 Transformer 对象
Transformer transformer = transformerFactory.newTransformer();
// 10、创建 DOMSource 对象
DOMSource domSource = new DOMSource(document);
// 11、创建 File 对象
String filePath = "I:\\code_workspace\\JavaSE_workspace\\JavaSE\\src\\cn\\com\\zfc\\lesson26\\xml\\CreateXmlFile.xml";
File file = new File(filePath);
// 12、创建 StreamResult 对象
StreamResult reStreamResult = new StreamResult(file);
transformer.transform(domSource, reStreamResult);
// 输出测试结果
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult); } catch (Exception e) {
e.printStackTrace();
} }
}

三、运行结果:CreateXmlFile.xml

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student id="student1">
<name>Tom</name>
<sex>Female</sex>
</student>
<student id="student2">
<name>Lucy</name>
<sex>Male</sex>
</student>
</students>

Java 操纵XML之创建XML文件的更多相关文章

  1. C#操作XML存取创建XML

    using System.Xml; #region 生成XML文档 /// <summary> ///  /// </summary> /// <param name=& ...

  2. java Ftp上传创建多层文件的代码片段

    StringBuilder sBuilder = new StringBuilder();            String[] pah = path.split("/");   ...

  3. Java根据html模板创建 html文件

    1.创建html的java代码 package com.tydic.eshop.util; import java.io.FileInputStream; import java.io.FileOut ...

  4. 关于Java里面File类创建txt文件重复???

    private JButton getOpenButton() { if (openButton == null) { openButton = new JButton(); openButton.s ...

  5. asp.net创建XML文件方法

    方法一:按照XML的结构一步一步的构建XML文档.    通过.Net FrameWork SDK中的命名空间"System.Xml"中封装的各种类来实现的 方法一:按照XML的结 ...

  6. 利用python 创建XML文件

    #coding=utf-8 from xml.etree import ElementTree import pdb def printNodeInfo(node): #node.tag 标签名称 # ...

  7. .NET 对 XML 进行创建,增加,删除,修改操作整理

    前言: 最近做了一个项目,程序A在一个服务器程序B在另一台服务器,然而主程序A需要访问程序B的图片集文件夹下载到本服务器上,为了防止多次对Web Services进行调用,在主程序A中创建一个XML文 ...

  8. Php 创建XML

    Php 创建XML  Php 创建XML并保存,学习示比例如以下: <? php try{ //创建DOMDocument 对象 $dom = new DOMDocument("1.0 ...

  9. java创建TXT文件并进行读、写、修改操作

    import java.io.*; /**  *   * 功能描述:创建TXT文件并进行读.写.修改操作  *        * @author <a href="mailto:zha ...

随机推荐

  1. spring boot 分布式事务实现(XA方式)

    关于spring boot 支持分布式事务,XA是常用的一种方式. 这里把相关的配置记下,方便以后使用. 首先配置两个不同的数据源 : 订单库.持仓库. /** * Created by zhangj ...

  2. [六字真言]2.嘛.异常定制和通用.md

    幻世当空 恩怨休怀 舍悟离迷 六尘不改 且怒且悲且狂哉! 最近一直在循环的一首歌! 丰富自己,比取悦他人更有力量.种下梧桐树,引得凤凰来.你若盛开,蝴蝶自来! 言归正传! 言归正传! 不要去大包大揽 ...

  3. bzoj千题计划253:bzoj2154: Crash的数字表格

    http://www.lydsy.com/JudgeOnline/problem.php?id=2154 #include<cstdio> #include<algorithm> ...

  4. poj 2947 Widget Factory (高斯消元解同余方程组+判断无解、多解)

    http://poj.org/problem?id=2947 血泪史: CE:poj的string类型要加string库,swap不能直接交换数组 WA: x[m-1]也有可能<3啊O(≧口≦) ...

  5. koa1.x获取原始body内容

    Node版本比较老,koa1.x配合koa-body-parser,默认koa-body-parser会把请求数据转成json对象, 然而有的时候需要获取原始的内容,不要转换,看波koa-body-p ...

  6. [整理]ASP.NET MVC 5

    1.入门 1.1官方资料 http://www.asp.net/mvc/overview/getting-started/introduction/getting-started 疑问: startu ...

  7. 第八集:魔法阵 NTT求循环卷积

    题目来源:http://www.fjutacm.com/Problem.jsp?pid=3283 题意:给两串长度为n的数组a和b,视为环,a和b可以在任意位置开始互相匹配得到这个函数的值,求这个函数 ...

  8. python3之安装、pip、setuptools

    1.python3安装 下载地址:https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz #安装环境centOS 7 #安装依赖包: yum ...

  9. shell expect的简单用法【转】

    用expect实现自动登录的脚本,网上有很多,可是都没有一个明白的说明,初学者一般都是照抄.收藏.可是为什么要这么写却不知其然.本文用一个最短的例子说明脚本的原理. 脚本代码如下:  ######## ...

  10. MVC Form验证 登陆和退出Cookies的设定和消除

    红色部分为重点 1.webconfig配置  <system.web>节点下添加 <authentication mode="Forms"> <for ...