需求:修改带有属性的xml 如需要修改下面title【一般不带有属性的修改方式比较容易,在此不演示】
<book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book>
准备:
一、jar包,这两个jar包可以用maven的porm引用也可以直接去网上下载(链接:https://pan.baidu.com/s/1V2f-s3FnEkkvmy--eD3-cw提取码:hk26)。
dom4j-1.6.1.jar jaxen-1.1-beta-8.jar
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1-beta-8</version> </dependency>
二、xml文件,这里使用xpah定位元素
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">啦啦啦</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
三、代码
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class demos1 { public static void main(String[] args) { String filePath = "E:\\Temp\\dd.xml"; String xpath = "//book[@category='WEB']/title[@lang='en']";//查询属性type='Creator' String values = "啦啦啦"; updateXml(filePath, xpath, values); } public static String updateXml(String filePath, String xpath, String values) { try { //获取tomcat下文件的相对路径 SAXReader reader = new SAXReader(); // FileInputStream f = new FileInputStream(filePath); File file=new File(filePath); Document document = reader.read(file); //dom4j读取 Element element = (Element) document.selectSingleNode(xpath);//得到name=Creator的元素 element.setText(values); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); writer.write(document); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "OK!"; } }