dom4j操作xml对象

时间:2022-03-07 12:47:35
     // 获取Documen对象
     public static Document getDocument(String path) throws Exception{
            // 解析器对象
           SAXReader reader = new SAXReader();
            // 解析
            return reader.read(path);
     }
     // 回写(XMLWriter)
     public static void writeXml(Document document,String path) throws Exception{
            // 格式
           OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置编码
           format.setEncoding( "UTF-8");
            XMLWriter writer = new XMLWriter (new FileOutputStream(path), format);
            // 进行回写
           writer.write(document);
            // 关闭流
           writer.close();
     }
// 使用工具类,操作XML
           Document document = MyXmlUtil.getDocument(MyXmlUtil. PATH);
            // 解析XML
            // 获取根节点(查文档)
           Element root = document.getRootElement();
            // 校验用户名或者邮箱是否重名
           List<Element> uList = root.elements("user");
            // 判断
            if(uList != null || uList.size() > 0){
                 // XML中查询,和传入过来做对比,如果相同,重名了,返回
                 // 从XML中获取的
                 for (Element u : uList) {
                      // 获取username 节点的文本内容
                      // u.element("username ").getText();
                     String xmlName = u.elementText("username");
                      // 获取传入进来的User 的名称
                     String uName = user.getUsername();
                      // 重名了,返回1
                      if(xmlName.equals(uName)){
                            return MyXmlUtil.NAMEEXIST;
                     }
                      // 获取xmlEamil
                     String xmlEmail = u.elementText( "email");
                     String uEamil = user.getEmail();
                      if(xmlEmail.equals(uEamil)){
                            return MyXmlUtil.EMAILEXIST;
                     }
                }
           }
            // 需要在XML添加节点
           Element uElement = root.addElement( "user");
            // 添加子节点
          uElement.addElement( "username").setText(user.getUsername());
          uElement.addElement( "password").setText(user.getPassword());
          uElement.addElement( "nickname").setText(user.getNickname());
          uElement.addElement( "email").setText(user.getEmail());
            // 回写
            MyXmlUtil.writeXml(document, MyXmlUtil .PATH );
            // 返回1 用户名重名了,返回是2邮箱重名,返回0注册成功
            return MyXmlUtil.SUCCESS;