使用dom4j修改XML文件内容

1、使用dom4j修改xml文件的属性、节点
public static int ModiXMLFile(String filename,String newfilename){
/** 返回操作结果, 0表失败, 1表成功*/
int intReturn = 0;

try {
SAXReader reader = new SAXReader();
Document document = reader.read(new File(filename));

/** 修改内容之一: 如果book节点中show属性的内容为yes,则修改成no*/
/** 先用xpath查找对象*/
List list = document.selectNodes("/books/book/@show");
Iterator it = list.iterator();
while(it.hasNext()){
Attribute attr = (Attribute)it.next();
if(attr.getValue().equals("yes")){
attr.setValue("no");
}
}

/**
* 修改内容之二: 把owner项内容改为Tshinghua
* 并在owner节点中加入date节点,date 节点的内容为2004-09-11,还为date 节点添加一个属性type
*/

list = document.selectNodes("/books/owner");
it = list.iterator();
if(it.hasNext()){
Element owner = (Element)it.next();
owner.setText("Tshinghua");
Element dateElement = owner.addElement("date");
dateElement.setText("2010-06-03");
dateElement.addAttribute("type", "你好");
}

/** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点*/
list = document.selectNodes("/books/book");
it = list.iterator();
while(it.hasNext()){
Element titleElement = (Element)it.next();
if(titleElement.getText().equals("threw")){
document.remove(titleElement);
}
}

OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)),format);
writer.write(document);
writer.close();

intReturn = 1;
} catch (Exception e) {
e.printStackTrace();
}

return intReturn;
}

你可能感兴趣的:(xml)