XmlUtil--Obj2Xml與Xml2Json

coding:


public class XmlUtil {

    public static final Logger log = LoggerFactory.getLogger(XmlUtil.class);

    /**
     * @param obj 傳入的對象
     * @return 返回對象轉換xml字符串
     */
    public static String objToXmlString(Object obj){
        log.info("開始將對象轉換爲xml格式字符串");
        String xmlString = "";
        //創建輸出 流
        StringWriter writer = new StringWriter();
        try {
            //jdk自帶的轉換類
            //傳入對象的class
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            //創建marshaller(指揮)通過它可以將xml與對象互相轉換 。對於一些不規範的xml格式它也可以進行規範調試
            Marshaller marshaller = context.createMarshaller();

            //格式化xml輸出格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            //編碼格式
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            //去掉默認報文頭
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

            //將對象輸出成XML形式
            marshaller.marshal(obj, writer);

            xmlString = writer.toString();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            log.error("轉換出錯!",e);
        }
        return xmlString;
    }



    public static JSONObject xml2Json(String xmlStr) throws JDOMException, IOException {
        if (StringUtils.isEmpty(xmlStr)) {
            return null;
        }
        xmlStr = xmlStr.replaceAll("\\\n", "");
        byte[] xml = xmlStr.getBytes("UTF-8");
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));

        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List<Element> node = element.getChildren();
        JSONObject obj = new JSONObject();
        List list = null;
        for (Element child : node) {
            list = new LinkedList();
            String text = child.getTextTrim();
            if (StringUtils.isBlank(text)) {
                if (child.getChildren().size() == 0) {
                    continue;
                }
                if (obj.containsKey(child.getName())) {
                    list = (List) obj.get(child.getName());
                }
                //遍歷child的子節點
                list.add(iterateElement(child));
                obj.put(child.getName(), list);
            } else {
                if (obj.containsKey(child.getName())) {
                    Object value = obj.get(child.getName());
                    try {
                        list = (List) value;
                    } catch (ClassCastException e) {
                        list.add(value);
                    }
                }
                //child無子節點時直接設置text
                if (child.getChildren().size() == 0) {
                    obj.put(child.getName(), text);
                } else {
                    list.add(text);
                    obj.put(child.getName(), list);
                }
            }
        }
        return obj;
    }


}

代碼是最好的教程!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章