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.FileWriter;
import java.io.IOException;
import java.util.List;
public class Update {
public static void main(String[] args) throws DocumentException, IOException {
SAXReader reader=new SAXReader();
//1、读取XML文件
Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml"));
//2、获取根元素
Element rootElement = document.getRootElement();
//获取指定元素
Element actions = rootElement.element("actions");
//获取根元素的所有子元素
List<Element> rootChildren = rootElement.elements();
for (Element child : rootChildren) {
List<Element> childChildren = child.elements();
if (childChildren!=null&&childChildren.size()>0) {
for (Element childChild : childChildren) {
//获取元素name属性
Attribute name = childChild.attribute("name");
if (name!=null) {
//修改属性值
name.setValue("nameUpdate");
}
List<Element> elements = childChild.elements();
if (elements!=null&&elements.size()>0) {
for (Element element : elements) {
//修改子元素值
element.setText("修改后的值");
}
}
}
}
}
//创建输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
//XML写入工具
XMLWriter writer=new XMLWriter(new FileWriter("update.xml"),format);
//写入文档至XML文件
writer.write(document);
//关闭流
writer.close();
}
}