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;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class Util {
public static void main(String[] args) {
// 创建SAXReader对象
SAXReader sr = new SAXReader();
// 关联xml
Document document = null;
try {
document = sr.read(new File("./src/main/resources/cityId.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
// 获取根元素
Element root = document.getRootElement();
// 获取标签
Element element = root.element("id");
// 在xml的某一个标签里修改一个属性
Attribute id = element .attribute("cityId");
id.setValue("sdfwaewaefw");
//element..addAttribute("cityId", "sfadfdsf"); //key相同,覆盖;不存在key,则添加
//指定文件输出的位置
FileOutputStream out = null;
try {
out = new FileOutputStream("./src/main/resources/cityId.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 指定文本的写出的格式:
OutputFormat format=OutputFormat.createPrettyPrint(); //有空格换行
format.setEncoding("UTF-8");
try {
//1.创建写出对象
XMLWriter writer=new XMLWriter(out,format);
//2.写出Document对象
writer.write(document);
//3.关闭流
writer.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<city>
<id cityId="aaaaaaaaaaa"/>
</city>