使用jdk类库对xml文件进行修改

一般对xml文件的操作以读居多,对xml文件的修改不是很常见,今天写项目的时候遇到,赶紧google了一把,整理了下写个小例子跟大家分享下。直接使用jdk5.0以上版本自带的api来解决。
准备一个xml文件:
[color=green][b]test.xml[/b][/color]

<?xml version="1.0" encoding="utf-8"?>
<javastyle>
<book>
<title>Thanking in java</title>
<author>(美)埃克尔 著,陈昊鹏 译</author>
<publisher>机械工业出版社</publisher>
<isbn>9787111213826</isbn>
<price>108.00</price>
</book>
</javastyle>



package com.javastyle.test;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class ModifyXML
{
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
//方便起见直接搞个绝对路径
File file = new File(
"E:\\MyEclipseWorkshop\\modifyxml\\src\\com\\javastyle\\testtest.xml");
Document doc = builder.parse(file);
XPathFactory pathFactory = XPathFactory.newInstance();
XPath xpath = pathFactory.newXPath();
// 使用xpath,找到需要的节点
XPathExpression pathExpression = xpath.compile("//price/text()");
Object result = pathExpression.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++)
{
System.out.println(nodes.item(i).getNodeValue());

nodes.item(i).setNodeValue("81.00");

// 注意不要忘记更新文件,否则只会更新缓存,不会真正更新文件
TransformerFactory tfFactory = TransformerFactory.newInstance();
Transformer tf = tfFactory.newTransformer();
StreamResult sResult = new StreamResult(file);
DOMSource source = new DOMSource(doc);
tf.setOutputProperty(OutputKeys.VERSION, "1.0");
tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(source, sResult);

System.out.println(nodes.item(i).getNodeValue());
}
}
}



[color=green][b]运行结果:[/b][/color]

<?xml version="1.0" encoding="utf-8"?>
<javastyle>
<book>
<title>Thanking in java</title>
<author>(美)埃克尔 著,陈昊鹏 译</author>
<publisher>机械工业出版社</publisher>
<isbn>9787111213826</isbn>
<price>81.00</price>
</book>
</javastyle>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值