总结使用dom4j和xpath对xml文件的增删改查

时间:2021-02-05 20:15:29

使用dom4j和xPath对xml文件进行增删改查,以最简单的联系人为例子

1.注意导入dom4j和xpath的jar包

2.代码如下:

/**
* 获取所有的联系人信息
* @return
* @throws DocumentException 
*/
public List<Contact> getAllContacts() throws DocumentException{
File file = new File("contact.xml");
if(!file.exists()){
return null;
}else{
Document doc = XmlUtil.getXmlDoc(file);
List<Node> contacts = doc.selectNodes("//contact");
List<Contact> list = new ArrayList<Contact>();
for(Node node : contacts){
Contact contact = new Contact();
contact.setId(node.selectSingleNode("./@id").getText());//获取属性Id
contact.setAge(node.selectSingleNode("./age").getText());//获取年龄
contact.setGender(node.selectSingleNode("./gender").getText());//获取性别
contact.setName(node.selectSingleNode("./name").getText());//姓名
contact.setPhone(node.selectSingleNode("./phone").getText());//手机号码
list.add(contact);
}
return list;
}
}



/**
* 添加联系人信息
* @param c
*/
public void addContact(Contact c){
File file = new File("contact.xml");
Document doc = null;
Element rootElem = null;
if(!file.exists()){
//如果文件不存在,表示还没有创建过xml文件
doc = DocumentHelper.createDocument();
//添加根元素
rootElem = doc.addElement("contact-list");
}else{
//如果文件已经存在则读取xml文件并获取根元素
try {
doc = XmlUtil.getXmlDoc(file);
} catch (DocumentException e) {
System.out.println("添加联系人失败!");
throw new RuntimeException(e);
}
rootElem = doc.getRootElement();
}
Element contact = rootElem.addElement("contact");
contact.addAttribute("id", c.getId());
contact.addElement("name").addText(c.getName());
contact.addElement("age").addText(c.getAge());
contact.addElement("gender").addText(c.getGender());
contact.addElement("phone").addText(c.getPhone());
//写出到文件中
try {
XmlUtil.writeXmlDoc(file, doc);
System.out.println("添加联系人成功!");
} catch (IOException e) {
System.out.println("添加联系人失败!");
throw new RuntimeException(e);
}
}


/**
* 修改联系人信息
* @param c
*/
public void updateContact(Contact c){
File file = new File("contact.xml");
//获取xml文件
try {
Document doc = XmlUtil.getXmlDoc(file);
Node elem = doc.selectSingleNode("//contact[@id='"+c.getId()+"']");
elem.selectSingleNode("./age").setText(c.getAge());
elem.selectSingleNode("./name").setText(c.getName());
elem.selectSingleNode("./gender").setText(c.getGender());
elem.selectSingleNode("./phone").setText(c.getPhone());
XmlUtil.writeXmlDoc(file, doc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}


/**
* 删除联系人信息
* @param id
*/
public void deleteContact(String id){
File file = new File("contact.xml");
//获取xml文件
try {
Document doc = XmlUtil.getXmlDoc(file);
Node elem = doc.selectSingleNode("//contact[@id='"+id+"']");
//删除节点
elem.detach();
XmlUtil.writeXmlDoc(file, doc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}


其中将读取Xml文件和写入xml文件的代码已经提取为公用代码,如下:


/**
* 读取指定的xml文件,获取Document对象
* @param file
* @return
* @throws DocumentException
*/
public static Document getXmlDoc(File file) throws DocumentException{
SAXReader reader = new SAXReader();
Document doc = reader.read(file);
return doc;
}

/**
* 将修改过的Document文件内容写入到xml中去
* @param file
* @param doc
* @throws IOException
*/
public static void writeXmlDoc(File file,Document doc) throws IOException{
OutputStream out = new FileOutputStream(file);
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(out, format);
writer.write(doc);
out.close();
}

结束!