xml转换之

1、XStream

    public static <T> T toBean(String xmlStr, Class<T> cls) {
        XStream xstream = new XStream(new DomDriver());
        xstream.processAnnotations(cls);
        xstream.ignoreUnknownElements();
        @SuppressWarnings("unchecked")
        T t = (T) xstream.fromXML(xmlStr);
        return t;
    }

    public static String toXml(Object obj) {
        XStream xstream = new XStream(new DomDriver("utf8"));
        xstream.processAnnotations(obj.getClass()); // 识别obj类中的注解
        /*
         // 以压缩的方式输出XML
         StringWriter sw = new StringWriter();
         xstream.marshal(obj, new CompactWriter(sw));
         return sw.toString();
         */
        // 以格式化的方式输出XML
        return xstream.toXML(obj);
    }

属性不对报错

ignoreUnknownElements(); 
ignoreUnknownElements(String pattern);

参考:http://my.oschina.net/JasonZhang/blog/228457

1、使用注解方式 http://www.blogjava.net/bolo/archive/2014/08/26/417353.html

2、使用代码方式 http://blog.csdn.net/xiaochunyong/article/details/7654523

 

2.xpath

也可以直接通过xpath来获取xml对应的节点属性值

 

 

待更新..

 

posted @ 2016-04-19 20:33  draem0507  阅读(234)  评论(0编辑  收藏  举报
View Code