Java对XML文件增删改查操作示例
作者:秋夜雨微凉 发布时间:2021-10-28 08:46:29
标签:Java,XML
本文实例讲述了Java对XML文件增删改查操作。分享给大家供大家参考,具体如下:
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
增删改查 Test.java
import java.io.File;
import java.io.FileOutputStream;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Element theBook = null, theElem = null, root = null;
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document xmldoc = (Document) db.parse(new File("Test.xml"));
root = xmldoc.getDocumentElement();
// --- 新建一本书开始 ----
theBook = xmldoc.createElement("book");
theElem = xmldoc.createElement("name");
theElem.setTextContent("新书");
theBook.appendChild(theElem);
theElem = xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem = xmldoc.createElement("memo");
theElem.setTextContent("新书的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本书开始 ----");
output(xmldoc);
// --- 新建一本书完成 ----
// --- 下面对《哈里波特》做一些修改。 ----
// --- 查询找《哈里波特》----
theBook = (Element) selectSingleNode("/books/book[name='哈里波特']",
root);
System.out.println("--- 查询找《哈里波特》 ----");
output(theBook);
// --- 此时修改这本书的价格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");// getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的".//price"。
System.out.println("--- 此时修改这本书的价格 ----");
output(theBook);
// --- 另外还想加一个属性id,值为B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外还想加一个属性id,值为B01 ----");
output(theBook);
// --- 对《哈里波特》修改完成。 ----
// --- 要用id属性删除《三国演义》这本书 ----
theBook = (Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- 要用id属性删除《三国演义》这本书 ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 删除后的XML ----");
output(xmldoc);
// --- 再将所有价格低于10的书删除 ----
NodeList someBooks = selectNodes("/books/book[price<10]", root);
System.out.println("--- 再将所有价格低于10的书删除 ---");
System.out.println("--- 符合条件的书有" + someBooks.getLength()
+ "本。 ---");
for (int i = 0; i < someBooks.getLength(); i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);
saveXml("Test1_Edited.xml", xmldoc);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将node的XML字符串输出到控制台
*
* @param node
*/
public static void output(Node node) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(node);
StreamResult result = new StreamResult();
result.setOutputStream(System.out);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查找节点,并返回第一个符合条件节点
*
* @param express
* @param source
* @return
*/
public static Node selectSingleNode(String express, Object source) {
Node result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
/**
* 查找节点,返回符合条件的节点集。
* @param express
* @param source
* @return
*/
public static NodeList selectNodes(String express, Object source) {
NodeList result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (NodeList) xpath.evaluate(express, source,
XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
/**
* 将Document输出到文件
* @param fileName
* @param doc
*/
public static void saveXml(String fileName, Document doc) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(doc);
StreamResult result = new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat
XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
希望本文所述对大家java程序设计有所帮助。
来源:https://blog.csdn.net/u013183865/article/details/32165289


猜你喜欢
- 首先当我们将Dwr3配置好以后,我们可以在浏览器中测试一下,查看一下我们配置的Dwr有没有生效,方法是http://localhost:[你
- 1. Text日常最常用的应该就是显示文字,所以有必要说一下Text控件。首先源码如下:@Composablefun Text(  
- package test001;import java.awt.event.ActionEvent;import java.awt.even
- 项目结构把源码 clone 下来 , 可以看到 retrofit 整体结构如下图 http包目录下就是一些http协议常用接口 , 比如 请
- 有人问我,怎么判断一个点是不是在多边形内,本来想着把这个多边形分成一个又一个三角形,如图, 然后判断这个点是不是在某个三角形中,如
- 本文实例为大家分享了Unity3D仿写Button面板事件绑定功能的具体代码,供大家参考,具体内容如下最近在做一个情节引导得项目。其中一个需
- 本文使用SpringBoot结合Redis进行简单的token鉴权。1.简介刚刚换了公司,所以最近有些忙碌,所以一直没有什么产出,最近朋友问
- 一、什么是桥接模式:桥接,顾名思义,就是用来连接两个部分,使得两个部分可以互相通讯,桥接模式的作用就是为被分离的抽象部分和实现部分搭桥。在现
- 加坐标可以使用https://mvnrepository.com/来查找先加以下坐标:使用的数据库介绍:配置连接数据库:spring: &n
- 和线程停止相关的三个方法/*中断线程。如果线程被wait(),join(),sleep()等方法阻塞,调用interrupt()会清除线程中
- 一.添加控件IrisSkin2.dll。方法:  
- RocketMQ发送消息我们在使用RocketMQ发送消息时,一般都会使用DefaultMQProducer,类型的代码如下:Default
- 从源代码树下载下来的最新Android源代码,是不包括内核代码的,也就是Android源代码工程默认不包含Linux Kernel代码,而是
- 前文常用的控件介绍了不少,现在就来讨论一下手机开发中常用到的画图。要掌握Android的画图,首先就要了解一下,基本用到的如下一些图形接口:
- @GetMapping注解携带参数方式今天突然发现,当我们根据id查询用户信息时,如果不想通过localhost:8080//findOne
- SpringMVC 中的Interceptor 拦截请求是通过HandlerInterceptor 来实现的。在SpringMVC 中定义一
- 1. 什么是单例模式单例模式指的是在应用整个生命周期内只能存在一个实例。单例模式是一种被广泛使用的设计模式。他有很多好处,能够避免实例对象的
- 在每一个窗体生成的时候,都会针对于当前的窗体定义InitializeComponent()方法,该方法实际上是由系统生成的对于窗体界面的定义
- 这几天恰好和朋友谈起了递归,忽然发现不少朋友对于“尾递归”的概念比较模糊,网上搜索一番也没有发现讲解地完整详细的资料,于是写了这么一篇文章,
- .NET包含一个特殊的Object类,可以接受任意的数据类型的值,当所传递或所赋值的类型不是一个特定的数据类型时,object类就提供了一种