Java 操纵XML之创建XML文件
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文件的更多相关文章
- C#操作XML存取创建XML
using System.Xml; #region 生成XML文档 /// <summary> /// /// </summary> /// <param name=& ...
- java Ftp上传创建多层文件的代码片段
StringBuilder sBuilder = new StringBuilder(); String[] pah = path.split("/"); ...
- Java根据html模板创建 html文件
1.创建html的java代码 package com.tydic.eshop.util; import java.io.FileInputStream; import java.io.FileOut ...
- 关于Java里面File类创建txt文件重复???
private JButton getOpenButton() { if (openButton == null) { openButton = new JButton(); openButton.s ...
- asp.net创建XML文件方法
方法一:按照XML的结构一步一步的构建XML文档. 通过.Net FrameWork SDK中的命名空间"System.Xml"中封装的各种类来实现的 方法一:按照XML的结 ...
- 利用python 创建XML文件
#coding=utf-8 from xml.etree import ElementTree import pdb def printNodeInfo(node): #node.tag 标签名称 # ...
- .NET 对 XML 进行创建,增加,删除,修改操作整理
前言: 最近做了一个项目,程序A在一个服务器程序B在另一台服务器,然而主程序A需要访问程序B的图片集文件夹下载到本服务器上,为了防止多次对Web Services进行调用,在主程序A中创建一个XML文 ...
- Php 创建XML
Php 创建XML Php 创建XML并保存,学习示比例如以下: <? php try{ //创建DOMDocument 对象 $dom = new DOMDocument("1.0 ...
- java创建TXT文件并进行读、写、修改操作
import java.io.*; /** * * 功能描述:创建TXT文件并进行读.写.修改操作 * * @author <a href="mailto:zha ...
随机推荐
- Spark记录-官网学习配置篇(二)
### Spark SQL Running the SET -v command will show the entire list of the SQL configuration. #scala/ ...
- JAVA-Servlet内容
Servlet重定向 HttpServletResponse接口的sendRedirect()方法可以用于将响应重定向到另一个资源,资源可能是servlet,jsp或html文件. 它接受相对和绝对U ...
- POJ 3252 Round Number(数位DP)
Round Numbers Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 6983 Accepted: 2384 Des ...
- 读asyncio模块源码时的知识补漏
硬着头皮看了一周的asyncio模块代码,了解了大概的执行流程,引用太多,成尤其是对象间函数的引用. 光是这么一段简单的代码: # coding: utf8 import asyncio import ...
- 五个案例让你明白GCD死锁(转)
转自:http://ios.jobbole.com/82622/ 死锁一直都是在使用多线程时,需要注意的一个问题.以前对同步.异步,串行.并行只有一个模糊的概念,想想也是时候整理一下了.再看看之前的博 ...
- google浏览器测试时清理缓存、强制不用缓存刷新快捷键(常用、效率)
Ctrl+Shift+Del 清除Google浏览器缓存的快捷键 Ctrl+Shift+R 重新加载当前网页而不使用缓存内容
- linux的内存文件系统tmpfs
在centos系统上自带的内存文件系统.这个tmpfs是temporary file system的意思. 一. 使用命令 df -h 查看tmpfs是否正在运行. Filesystem Size U ...
- free vmstat查看内存及系统调优【转】
内存查看 查看内存是否存在瓶颈,使用top指令看比较麻烦,而free命令更为直观: [/home/weber#]free total used free shared buffers cached M ...
- elasticsearch分别在windows和linux系统安装
WINDOWS系统安装1.安装JDKElastic Search要求使用较高版本JDK,本文使用D:\DevTools\jdk1.8.0_131,并配置环境变量 2.安装Elastic Search官 ...
- 09 Go 1.9 Release Notes
Go 1.9 Release Notes Introduction to Go 1.9 Changes to the language Ports ppc64x requires POWER8 Fre ...