Object to XML

Eave 2016.08.10 23:44

需要使用到的JAR包:

xstream-1.4.7.jar

dom4j-1.6.1.jar

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.qianyan.message.request.TextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class Xml
{
    public static void main(String[] args)
    {
        String xml = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>";

        XStream xStream = new XStream(new DomDriver());
        xStream.alias("xml", TextMessage.class);
        
        // XML To Object
        TextMessage textMessage = (TextMessage) xStream.fromXML(xml);

        // Object To XML
        TextMessage text = new TextMessage();
        text.setContent("qianyan");
        String xmlString = xStream.toXML(text);
    }

    /**
     * XML转Map
     * @param  xml   XML字符串
     * @return       [description]
     */
    @SuppressWarnings("unchecked")
    public static Map<String,String> xmlToMap(String xml)
    {
        Map<String,String> map = new HashMap<String,String>();
        Document doc = null;
        try
        {
            // 将字符串转为XML
            doc = DocumentHelper.parseText(xml);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            // 获取根节点下所有节点
            List<Element> list = rootElt.elements();
            // 遍历节点
            for(Element element : list)
            {
                // 节点的name为map的key,text为map的value
                map.put(element.getName(), element.getText());
            }
        }
        catch (DocumentException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 读取XML文件
     * @param xml
     */
    public static void readXml(String xml)
    {
        // 创建SAXReader对象
        SAXReader saxReader = new SAXReader();
        File file = new File(xml);
        try
        {
            // 读取文件 转换成Document
            Document document = saxReader.read(file);
            // 获取根节点元素对象
            Element element = document.getRootElement();
            // 获取某个节点的值
            Element memberElement = rootElement.element("ToUserName");
            String val = memberElement.getTextTrim();
            System.out.println(element.getName());
            listNodes(element);
        }
        catch (DocumentException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (DocumentException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void listNodes(Element element)
    {
        // 遍历
        // 首先获取当前节点的所有属性节点
        List<Attribute> list = element.attributes();
        // 遍历属性节点
        for(Attribute attribute : list)
        {
            System.out.println(attribute.getName() + ":" + attribute.getValue());
        }
        // 如果当前节点内容不为空,则输出
        if(!element.getTextTrim().equals(""))
        {
            System.out.println(element.getName() + ":" + element.getStringValue());
        }
        // 同时迭代当前节点下面的所有子节点
        // 使用递归
        Iterator<Element> iterator = element.elementIterator();
        while(iterator.hasNext())
        {
            Element e = iterator.next();
            listNodes(e);
        }
    }
}