使用dom4j操作xml文档

1. 获取文档对象:
public static Document getDocument(String str){
        File file=new File(str);
        SAXReader reader = new SAXReader();
        Document document = null;
        try
        {
            FileReader fr= new FileReader(file);
            document = reader.read(fr);
        } catch (FileNotFoundException e)
        {
                    e.printStackTrace();
        } catch (DocumentException e)
        {
            e.printStackTrace();
        }
        return document;
       
    }

2. 保存文档对象
public void saveDoc(String strXml, Document document) {
try {
XMLWriter output = new XMLWriter(new FileWriter(new File(strXml)));
//美化格式
OutputFormat format=new OutputFormat(" ",true);
OutputFormat.createPrettyPrint();
output.write(document);
output.close();

} catch (IOException e) {
logger.error("-------->document save failed:-->"+e.getMessage());
e.printStackTrace();

}
}
3. 检验一个节点是否已经存在
public boolean isUserExists(User user, String strXml) {
String nodes = "//users/user[@userName='" + user.getUserName() + "']";
// strXml:like : D:/workspace/on-nets-phaseII/src/config/test.xml
Document document = ConfigFileTool.getDocument(strXml);
// nodes的数据形式:"//roles/role"
List<Object> userList = document.selectNodes(nodes);
if (null != userList && userList.size() > 0) {
return false;
}

return true;
}
4. 添加一个节点:
public boolean addUser(User user, String strXml) {
if (isUserExists(user, strXml)) {
String uid = getStr();
Document document = ConfigFileTool.getDocument(strXml);
List list = document.selectNodes("users");
Element root = (Element) list.get(0);
Element userElement = root.addElement("user");
userElement.addAttribute("userId", uid);
userElement.addAttribute("userName", user.getUserName());
userElement.addAttribute("pwd", user.getPwd());
userElement.addAttribute("roles", user.getRoles());
saveDoc(strXml, document);
return true ;

}else{
logger.error("can't add the same user");
  return false;
 
}
}
5. 删错一个节点
public boolean delUser(String uname, String strXml) {
String nodes = "//users/user[@userName='" + uname + "']";
Document document = ConfigFileTool.getDocument(strXml);
List<Object> userList = document.selectNodes(nodes);
Element userEle = (Element) userList.get(0);
Element root = document.getRootElement();
boolean bl = userEle.getParent().remove(userEle);
// boolean bl=root.remove(userEle);
saveDoc(strXml, document);
return bl;

}
6. 修改一个节点
public boolean modifyUser(User user, String strXml) {
String nodes = "//users/user[@userId=" + user.getUserId() + "]";
// strXml:like : D:/workspace/on-nets-phaseII/src/config/test.xml
Document document = ConfigFileTool.getDocument(strXml);
// nodes格式"//roles/role"
List<Element> userList = document.selectNodes(nodes);
if (null != userList && userList.size() > 0) {
Element userEle = userList.get(0);
userEle.attribute("userName").setValue(user.getUserName());
userEle.attribute("pwd").setValue(user.getPwd());
userEle.attribute("roles").setValue(user.getRoles());
saveDoc(strXml, document);
return true;
}
return false;
}
7. 根据某个节点属性,来查询节点
public List<Element> findUserByName(String username, String strXml) {
String nodes = "//users/user[@userName='" + username + "']";
// strXml:like : D:/workspace/on-nets-phaseII/src/config/test.xml
Document document = ConfigFileTool.getDocument(strXml);
// nodes格式"//roles/role"
List<Element> userList = document.selectNodes(nodes);
return userList;

}
8. 获取所有的节点
public List<Element> findAllUsers(String strXml) {
String nodes = "//users/user";
// strXml:like : D:/workspace/XXX/src/config/test.xml
Document document = ConfigFileTool.getDocument(strXml);
// nodes格式"//roles/role"
List<Element> userList = document.selectNodes(nodes);

return userList;
}
9.动态查询:
public List findUsers(String uname, String role, String strXml) {
StringBuffer strbuf = new StringBuffer("//users/user");
//System.out.println(">>>>>>>>" + role);
if (null == uname) {
uname = "";
}
if (null == role) {
role = "";
}
if ("".equals(uname) && "".equals(role)) {

}
if ("".equals(uname) && !"".equals(role)) {
strbuf.append("[@roles='" + role + "']");
}
if (!"".equals(uname) && "".equals(role)) {
strbuf.append("[@userName='" + uname + "']");

}
if (!"".equals(uname) && !"".equals(role)) {
strbuf.append("[@userName='" + uname + "']");
strbuf.append("[@roles='" + role + "']");

}
String nodes = strbuf.toString();
// strXml:like : D:/workspace/on-nets-phaseII/src/config/test.xml
Document document = ConfigFileTool.getDocument(strXml);
// nodes格式"//roles/role"
List userList = document.selectNodes(nodes);

return userList;
}

个人扒文档整的,各位大侠有何指正,忘不吝赐教

你可能感兴趣的:(xml)