我们用到的包是dom4j-1.6.1
一般情况下我们还应该用到包jaxen-1.1.1,它是对一些异常进行处理的,如果没有,会报错。
1 | import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlUtil {
private SAXReader reader;
private Document document;
private File xmlFile;
private XMLWriter writer;
/*初始化saxreader,并读取xml文件
*/
public XmlUtil(String fileName) throws Exception {
xmlFile = new File(fileName);
reader = new SAXReader();
document = reader.read(xmlFile);
}
/**
* @param path 节点的全路径 /drawpie/pie/pies
* @param name 新增节点的名称
* @param content 节点的内容
*/
public void addNode(String path,String name,String content,Vector<NodeAttri> attributes){
Element parent =(Element)document.selectSingleNode(path);
Element addnode=parent.addElement(name);
addnode.addText(content);
if(attributes!=null){
for(int i=0;i<attributes.size();i++){
NodeAttri aa=attributes.get(i);
addnode.addAttribute(aa.att,aa.value);
}
}
System.out.println("新增节点成功");
System.out.println(document.asXML());
}
/**
* @param removeNodePath 从根节点开始的将要删除节点的路径 /drawpie/pie/pies (将要删除pies节点)
*/
public void removeNode(String removeNodePath){
Element removeElement =(Element)document.selectSingleNode(removeNodePath);
removeElement.getParent().remove(removeElement);
}
/**
* @return
* 将修改后的xml保存
*/
public boolean save(){
try {
writer = new XMLWriter(new FileOutputStream(xmlFile));
writer.write(document);
writer.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
|