浏览 2956 次
锁定老帖子 主题:使用jdk类库对xml文件进行修改
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-01-31
最后修改:2010-06-20
准备一个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> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |