java中修改xml文件内容_修改所有xml文件中的某些内容

我的需求是:将所有项目的pom.xml中的ip地址替换

package com.company;

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;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

public class Main {

public static void main(String[] args) throws IOException, DocumentException {

test("D:\\JavaProjects\\");

}

private static void test(String fileDir) throws IOException, DocumentException {

List fileList = new ArrayList();

File file = new File(fileDir);

File[] files = file.listFiles();// 获取目录下的所有文件或文件夹

if (files == null) {// 如果目录为空,直接退出

return;

}

// 遍历,目录下的所有文件

for (File f : files) {

if (f.isFile() && "pom.xml".equals(f.getName())) {

fileList.add(f);

} else if (f.isDirectory()) {

test(f.getAbsolutePath());

}

}

for (File f1 : fileList) {

System.out.println(f1.getAbsolutePath()+"----------------------------------------------");

XML(f1);

}

}

public static void XML(File f1) throws DocumentException, IOException {

/*

* 2.java修改xml

*/

// 创建SAXReader对象

SAXReader sr = new SAXReader(); // 需要导入jar包:dom4j

sr.setEncoding("UTF8");//这里设置文件编码

// 关联xml

Document document = sr.read(f1);

// 获取根元素

Element root = document.getRootElement();

getNodes(root);

// 调用下面的静态方法完成xml的写出

saveDocument(document, f1);

}

/**

* 从指定节点开始,递归遍历所有子节点

*

* @author chenleixing

*/

public static void getNodes(Element node) {

System.out.println("--------------------");

//当前节点的名称、文本内容和属性

System.out.println("当前节点名称:" + node.getName());//当前节点名称

System.out.println("当前节点的内容:" + node.getTextTrim());//当前节点名称

if (node.isTextOnly()) {

String textTrim = node.getText();

if (textTrim!=null) {

if (textTrim.contains("10.88.99.2")) {

String s = textTrim.replaceAll("10\\.88\\.99\\.2", "10.88.88.176");

node.setText(s);

}

}

}

//递归遍历当前节点所有的子节点

List listElement = node.elements();//所有一级子节点的list

for (Element e : listElement) {//遍历所有一级子节点

getNodes(e);//递归

}

}

// 下面的为固定代码---------可以完成java对XML的写,改等操作

public static void saveDocument(Document document, File xmlFile) throws IOException {

Writer osWrite = new OutputStreamWriter(new FileOutputStream(xmlFile));// 创建输出流

OutputFormat format = OutputFormat.createPrettyPrint(); // 获取输出的指定格式

format.setEncoding("UTF-8");// 设置编码 ,确保解析的xml为UTF-8格式

XMLWriter writer = new XMLWriter(osWrite, format);// XMLWriter

// 指定输出文件以及格式

writer.write(document);// 把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)

writer.flush();

writer.close();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值