java读取并修改xml文件

java读取并修改xml文件

java如何读取xml并且修改xml文件呢?代码如下:

//复制模板xnl
File file = new File(xmlSavePath + "/mb.xml");
File copyFile = new File(xmlSavePath + "/" + 文件名称 + ".xml");
FileUtils.copyFile(file, copyFile);

//1、创建 DocumentBuilderFactory 对象,用来创建 DocumentBuilder 对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

// 2、创建 DocumentBuilder 对象,用来将 XML 文件 转化为 Document 对象
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

// 3、创建 Document 对象,解析 XML 文件
Document document = documentBuilder.parse(copyFile);

//获取PROCESSOR下的属性
Node processor = document.getElementsByTagName("PROCESSOR").item(0);
NamedNodeMap processors = processor.getAttributes();
//修改path属性
processors.getNamedItem("path").setTextContent(systemConfig.getAnalysisToolValus());

// 4、创建 TransformerFactory 对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();

// 5、创建 Transformer 对象
Transformer transformer = transformerFactory.newTransformer();

// 6、创建 DOMSource 对象
DOMSource domSource = new DOMSource(document);

// 7、创建 StreamResult 对象
StreamResult reStreamResult = new StreamResult(copyFile);
transformer.transform(domSource, reStreamResult);

xmlSavePath 是笔者在yml中配置的xml保存的地址

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值