本文主要介绍如何在已经存在的XML文件中,对节点添加属性的操作。
//filePath:XML文件的绝对路径
public static void xmlUpdateDemo(String filePath) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
org.jdom.Document doc = (org.jdom.Document) builder.build(filePath);
//取得根节点
Element root = (Element) doc.getRootElement();
//设置子节点的属性值
root.getChild("SonName").setAttribute("Score", "A+");
//将根节点重新设置到doc里
doc.setRootElement(root);
//新建XMLOutputter输出类
XMLOutputter XMLOut = new XMLOutputter();
//重新定位输出XML文件,这里直接覆盖原文件
XMLOut.output(doc, new FileOutputStream(filePath));
//清空类资源
XMLOut = null;
}