dom4j修改xml文件并保存

package xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Attribute;
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 ReviseXmlFile {

	public static void main(String[] args) {
		run();
	}

	private static void run() {

		 File file = new File("F:/aaa/xml/src/server.xml");
		
		 SAXReader reader = new SAXReader();
		 try {
			Document doc = reader.read(file);
			//获取根目录
			Element rootElement = doc.getRootElement();
			//获取指定节点
			Element node = (Element) doc.selectSingleNode("/Server/Service/Connector[@protocol='AJP/1.3']");
			//获取属性
			Attribute attribute = node.attribute("port");
			//设置属性值
			attribute.setValue("6666");
			//格式化为缩进格式
			OutputFormat format = OutputFormat.createPrettyPrint();
			//设置编码格式
			format.setEncoding("UTF-8");
			try {
				XMLWriter writer = new XMLWriter(new FileWriter(file),format);
				//写入数据
				writer.write(doc);
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 
		
	}
	
	
}


你可能感兴趣的:(dom4j修改xml文件并保存)