论坛首页 Java企业应用论坛

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

浏览 2950 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-31   最后修改:2010-06-20
一般对xml文件的操作以读居多,对xml文件的修改不是很常见,今天写项目的时候遇到,赶紧google了一把,整理了下写个小例子跟大家分享下。直接使用jdk5.0以上版本自带的api来解决。
准备一个xml文件:
test.xml
<?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());
		}
	}
}



运行结果:
<?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>






论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics