• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

xml与java对象转换-(Unmarshaller.unmarshal)

java 海叔叔 4年前 (2021-11-03) 42次浏览 已收录 0个评论

XML和javabean相互转换

public static String beanToXML(Class c , Object object) throws JAXBException {
    String xml = null;
    JAXBContext context = JAXBContext.newInstance(c);
    Marshaller m =context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    Writer w = new StringWriter();
    m.marshal(object, w);
    xml = w.toString();
    return xml;
}
public static <javaBean> bean xmlToBean(String xml, javaBean bean) throws JAXBException{
    JAXBContext context = JAXBContext.newInstance(bean.getClass());
    Unmarshaller um =context.createUnmarshaller();
    StringReader sr = new StringReader(xml);
    bean = (javaBean)um.unmarshal(sr);
    return bean;
}

另外还有一种:Castor实现XML与Java的互转。
下面写个简单例子,测试下Castor:
bean:

package ex1;
 
import java.io.Serializable;
import java.util.*;
 
public class Foo implements Serializable {
 
        private String name;
        private Date birthday = new Date();
        private List adds = new ArrayList(0);
        private Map map =    new HashMap(0);
 
        public Foo() {
        }
 
        public Foo(String name) {
                this.name = name;
        }
 
        public String getName() {
                return name;
        }
 
        public void setName(String name) {
                this.name = name;
        }
 
        public Date getBirthday() {
                return birthday;
        }
 
        public void setBirthday(Date birthday) {
                this.birthday = birthday;
        }
 
        public List getAdds() {
                return adds;
        }
 
        public void setAdds(List adds) {
                this.adds = adds;
        }
 
        public Map getMap() {
                return map;
        }
 
        public void setMap(Map map) {
                this.map = map;
        }
}

test类:

package ex1;
 
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
 
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Map;
 
public class MarshalTester {
 
        public static void main(String[] args) {
                testMarshaller();
                testUnMarshaller();
        }
 
        /**
         * java->XML
         */
        public static void testMarshaller() {
                try {
                        Foo f = new Foo("foo");
                        f.getAdds().add("zhengzhou");
                        f.getAdds().add("xian");
                        f.getMap().put("a", "aaa");
                        f.getMap().put("b", "bbb");
                        FileWriter writer = new FileWriter("foo.xml");
                        Marshaller marshaller = new Marshaller(writer);
                        marshaller.setEncoding("GBK");
                        marshaller.marshal(f);
                } catch (Exception e) {
                        e.printStackTrace(System.err);
                }
        }
 
        /**
         * XML->java
         */
        public static void testUnMarshaller() {
                try {
                        FileReader reader = new FileReader("D:\\teststu\\testcastor\\foo.xml");
                        Foo foo = (Foo) Unmarshaller.unmarshal(Foo.class, reader);
                        System.out.println("Name: " + foo.getName());
                        System.out.println("Birthday: " + foo.getBirthday());
                        for (Object s : foo.getAdds()) {
                                System.out.println("Add: " + s.toString());
                        }
 
                        for (Object o : foo.getMap().entrySet()) {
                                Map.Entry e = (Map.Entry) o;
                                System.out.println("Map: " + e.getKey() + "--" + e.getValue());
                        }
 
                } catch (Exception e) {
                        System.err.println(e.getMessage());
                        e.printStackTrace(System.err);
                }
        }
}

生成的xml文件如下:

foo.xml

<?xml version="1.0" encoding="GBK"?>
<foo>
        <name>foo</name>
        <birthday>2010-04-30T18:01:59.375+08:00</birthday>
        <map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com"
                 xsi:type="java:org.exolab.castor.mapping.MapItem">
                <key xsi:type="java:java.lang.String">a</key>
                <value xsi:type="java:java.lang.String">aaa</value>
        </map>
        <map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com"
                 xsi:type="java:org.exolab.castor.mapping.MapItem">
                <key xsi:type="java:java.lang.String">b</key>
                <value xsi:type="java:java.lang.String">bbb</value>
        </map>
        <adds xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com"
                    xsi:type="java:java.lang.String">zhengzhou
        </adds>
        <adds xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com"
                    xsi:type="java:java.lang.String">xian
        </adds>
</foo>

运行反解组测试方法:

log4j:WARN No appenders could be found for logger (org.castor.core.util.AbstractProperties).
log4j:WARN Please initialize the log4j system properly.
Name: foo
Birthday: Fri Apr 30 18:01:59 CST 2010
Add: zhengzhou
Add: xian
Map: a–aaa
Map: b–bbb

Process finished with exit code 0

黄色部分是有效输出!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:xml与java对象转换-(Unmarshaller.unmarshal)
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址