当前位置: 首页 > 工具软件 > DOM Treemap > 使用案例 >

dom4j 常用操作

芮化
2023-12-01

 

 

 

package com.wanbang.wbyyb.common.util;

import com.alibaba.fastjson.JSONObject;
import com.wanbang.wbyyb.common.constant.ErrorEnum;
import com.wanbang.wbyyb.common.exception.BusinessException;
import com.wanbang.wbyyb.service.payment.impl.PaymentServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class XmlUtils {
    private static final Logger logger = LoggerFactory.getLogger(PaymentServiceImpl.class);

    /**
     * 根据xml标签名的ASCII码正序排列的xml
     * @param filePath
     * @return
     */
    public static Document getXml(String filePath){
        Document document = null;
        try{
            Resource resource = null;
            if (!StringUtils.isEmpty(filePath))
                resource = new ClassPathResource(filePath);
            else
                throw new BusinessException(ErrorEnum.ERROR_PARAM);

            File file = resource.getFile();

            /**
             * 读取xml转有序map
             */
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element root = doc.getRootElement();
            Iterator iterator = root.elementIterator();
            Map<String,Object> map =  new TreeMap<>();
            while (iterator.hasNext()) {
                Element element = (Element) iterator.next();
                String key = element.getName();
                String value = element.getText();
                map.put(key, value);
            }

            /**
             * 有序map转xml
             */
            document = DocumentHelper.createDocument();
            Element newRoot = document.addElement("xml");
            Set<String> keys = map.keySet();
            for(String k:keys) {
                newRoot.addElement(k).addText(map.get(k).toString());
            }
        } catch (IOException e) {
            logger.error("com.wanbang.wbyyb.service.payment.impl: ",e);
        } catch (DocumentException e) {
            logger.error("com.wanbang.wbyyb.service.payment.impl:",e);
        }
        return document;
    }public static Object xml2Json(String xmlStr){
        JSONObject jsonObject = new JSONObject();
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            Element element = document.getRootElement();
            Iterator iterator = element.elementIterator();
            while (iterator.hasNext()) {
                Element ele = (Element)iterator.next();
                jsonObject.put(ele.getName(), ele.getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


 
  
}

 

 

    @Test
    public void createTest() {
        Document doc = DocumentHelper.createDocument();
        //创建一个名为xml的根节点,因为是第一个创建,所以是根节点,再通过doc创建一个则会报错。
        Element root = doc.addElement("xml");
        Element codeEle = root.addElement("return_code");
        Element msg = root.addElement("return_msg");
        codeEle.addCDATA("SUCCESS");  //生成结果<return_code><![CDATA[SUCCESS]]></return_code>
        codeEle.addAttribute("id", "101"); //添加属性
        msg.setText("SUCCESS"); //生成结果<return_code>SUCCESS</return_code>
        msg.setText("<![CDATA[SUCCESS]]>"); //生成结果<return_msg>&lt;![CDATA[SUCCESS]]&gt;</return_msg>
        System.out.println(doc.asXML());  //xml转String
    }

 

转载于:https://www.cnblogs.com/jxlsblog/p/dom4j.html

 类似资料: