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. Go_21: Golang 中 time 包的使用二

    常量声明: const TimeLayout = "2006-01-02 15:04:05" 这是个奇葩,必须是这个时间点,据说是 go 诞生之日, 记忆方法:6-1-2-3-4- ...

  2. Django中Celery http请求异步处理(四)

    Django中Celery http请求异步处理 本章延续celery之前的系列 1.settings配置 2.编写task jib_update_task任务为更新salt jid数据 3.url设 ...

  3. Codeforces 923 C. Perfect Security

    http://codeforces.com/contest/923/problem/C Trie树 #include<cstdio> #include<iostream> us ...

  4. CF876 F 思维 枚举

    给你n个数,问有几个区间满足,区间内或操作大于区间内的任意数. 首先可以知道,两数或操作的结果必定不会小于两者间的最大值,也就是说对于一个区间中,不合法的状态只有两值或相等.那么我们可以考虑枚举每个数 ...

  5. Linux下sh文件运行及桌面环境双击运行sh文件

    sh文件运行: 1.修改为可执行权限: chmod u+x hello.sh 2.运行 ./hello.sh 3.不使用可执行权限修改,用sh直接运行 sh ./hello.sh 桌面环境双击运行sh ...

  6. Django Book学习笔记(下)

    Django的Session框架 对于Django加密,大致使用这样的格式: hashtype$salt$hash 原因? 一次哈希是一次单向的加密过程,你能容易地计算出一个给定值的哈希码,但是几乎不 ...

  7. CSSOM

    概要 狭义的 DOM API 仅仅包含 DOM 树形结构相关的内容. DOM 中的所有的属性都是用来表现语义的属性,CSSOM 的则都是表现的属性. CSSOM 是 CSS 的对象模型,在 W3C 标 ...

  8. vue中,写在methods里的B方法去调A方法的数据,访问不到?

    今天在写项目的时候,发现了一个京城性忽略的问题,在vue的methods的方法里面定义了两个方法,如下: getTaskList() { api.growthDetails.taskList({ ap ...

  9. 利用overflow-x实现横向滚动的xiaoguo

    在进行app开发中经常遇到横向滚动的效果,相信很多人都是用js写的吧,其实用css的overflow-x也可以写出啦哦~~~ (1)介绍overflow-x: 1)浏览器支持 所有主流浏览器都支持 o ...

  10. Javascript - LayUI库的流加载

    LayUI库的流加载 用的LayUI-v2.2.45,将整个包解压缩后添加到项目,引入两个文件即可,不需要引入Jquery,此库自带: <link href="../js/layui- ...