java 读写xml文件

maven依赖:dom4j依赖包

dom4j
dom4j
1.6.1

public static void RWXmlFile() throws Throwable//方便抛出异常,直接抛出Throwable
{
String pom = “D:\example\test\spi-impl\pom.xml”;
//读取xml文件,这里的例子是spring工程的pom文件
SAXReader reader = new SAXReader();
Document document = reader.read(new File(pom));
Element root = document.getRootElement();
//根据标签层级,逐层解析xml
List elements = root.element(“build”).element(“plugins”).elements();
List elements1 = elements.get(0).element(“executions”).element(“execution”)
.element(“configuration”).element(“artifactItems”).elements();
for (int i = 0; i < elements1.size(); i++) {
//对xml文件进行逻辑处理,这里只是对juint和slf4j版本号替换(随便写得版本号不知道对不对)
if (elements1.get(i).element(“groupId”).getStringValue().equals(“junit”)) {
elements1.get(i).element(“version”).setText(“4.10”);
} else if (elements1.get(i).element(“groupId”).getStringValue().equals(“org.slf4j”)) {
elements1.get(i).element(“version”).setText(“1.7.6”);
}
}
//向指定文件写入读出来并修改的内容
Writer out = new PrintWriter(pom);
OutputFormat format = new OutputFormat("\t", true);
//去掉原来的空白(\t和换行和空格)!
format.setTrimText(true);
XMLWriter writer = new XMLWriter(out, format);
// 把document对象写到out流中。
writer.write(document);
out.close();
writer.close();
}

你可能感兴趣的:(java)