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保存的地址
版权声明:本文为qq_47870876原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。