使用JAXB时,xml与java对象互转以及初始情况下直接由模板xml生成javabean

在日常开发中有时会使用到xml来实现服务器间的数据交互,但是拼凑xml有时会耗费大量的时间甚至会出很多错误,作为java开发者我们如果能用直接操作java对象来处理当时是最好的,只需要在整理好数据对像后调用统一的访问方法即可,这时候我们可以使用JAXB


要使用JAXB,需要一个与xml模板对应的javabean,比如

xml模板:

<?xml version="1.0" encoding="UTF-8"?>
<testList>
	<test>
		<name></name>
		<age></age>
	</test>
</testList>

对应javabean文件:

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2017.09.26 at 04:39:37 PM CST 
//


package com.test;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for anonymous complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <choice maxOccurs="unbounded" minOccurs="0">
 *         <element name="test">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *                   <element name="age" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </choice>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "test"
})
@XmlRootElement(name = "testList")
public class TestBean {

    protected List<TestBean.Test> test;

    /**
     * Gets the value of the test property.
     * 
     * <p>
     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a <CODE>set</CODE> method for the test property.
     * 
     * <p>
     * For example, to add a new item, do as follows:
     * <pre>
     *    getTest().add(newItem);
     * </pre>
     * 
     * 
     * <p>
     * Objects of the following type(s) are allowed in the list
     * {@link TestBean.Test }
     * 
     * 
     */
    public List<TestBean.Test> getTest() {
        if (test == null) {
            test = new ArrayList<TestBean.Test>();
        }
        return this.test;
    }


    /**
     * <p>Java class for anonymous complex type.
     * 
     * <p>The following schema fragment specifies the expected content contained within this class.
     * 
     * <pre>
     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *         <element name="age" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     * </pre>
     * 
     * 
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "name",
        "age"
    })
    public static class Test {

        protected String name;
        protected String age;

        /**
         * Gets the value of the name property.
         * 
         * @return
         *     possible object is
         *     {@link String }
         *     
         */
        public String getName() {
            return name;
        }

        /**
         * Sets the value of the name property.
         * 
         * @param value
         *     allowed object is
         *     {@link String }
         *     
         */
        public void setName(String value) {
            this.name = value;
        }

        /**
         * Gets the value of the age property.
         * 
         * @return
         *     possible object is
         *     {@link String }
         *     
         */
        public String getAge() {
            return age;
        }

        /**
         * Sets the value of the age property.
         * 
         * @param value
         *     allowed object is
         *     {@link String }
         *     
         */
        public void setAge(String value) {
            this.age = value;
        }

    }

}



java对象转xml


此模板中假设testlist是个团队,我们要把每个人test的信息存入,信息是姓名name和年龄age,可以先用java对象进行以下操作:

TestBean test = new TestBean();
        List<TestBean.Test> testDataList = test.getTest();
        TestBean.Test testData = new TestBean.Test();
        testData.setName("aa");
        testData.setAge("11");
        testDataList.add(testData);

这就将一个名叫aa年龄11的人的信息加入了,接着我们写一个公共转换方法:

    public static String JObjToXml(Object obj, String encoding)
    {
        String result = null;
        try
        {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

然后只要调用即可:

System.out.println(JObjToXml(test, "UTF-8"));
输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testList>
    <test>
        <name>aa</name>
        <age>11</age>
    </test>
</testList>




xml转Java对象

模板依然同上,只需下面这个方法:

@SuppressWarnings("unchecked")
    public static <T> T xmlToJavaObj(String xml, Class<T> c)
    {
        T t = null;
        try
        {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T)unmarshaller.unmarshal(new StringReader(xml));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return t;
    }

调用时传入xml字符串及要转换的javaclass即可,注意模板要对应

String xmlStr = "<?xml version=\"1.0\" encoding=\"utf8w2\" standalone=\"yes\"?><testList><test><name>aa</name><age>11</age></test></testList>";
TestBean convertTestBean = xmlToJavaObj(xmlStr, TestBean.class);
System.out.println(convertTestBean.getTest().get(0).getName());
System.out.println(convertTestBean.getTest().get(0).getAge());

输出结果:

aa
11


如何得到xml模板对应的javabean文件

方法1:手动写入,这个在这里不作太多说明,写javabean的时候需要注意属性名及注释不要有错

方法2:使用xsd及xjc根据xml模板转换:

1.准备工作:你需要有xsd.exe这个程序,一般是在Microsoft SDKs\Windows\v7.1\Bin这个路径下,前提是你已经安装了Microsoft SDK,如果没有就去官网下载安装一个(地址:https://www.microsoft.com/en-us/download/details.aspx?id=8279     我是win7所以装的7.1,可自行选择);其次你需要有JDK(基本都有否则怎么用JAXB),xjc.exe的路径在jdk1.7.0_79\bin下;最后你需要一个已经整理好的xml模板(后面就使用文章中的这个模板)


2.打开cmd,进入到xsd所在目录,运行xsd D:\xsdTest\test.xml /out:D:\xsdTest ,至于具体参数怎么用敲个xsd /?自己看吧,之后在目标目录生成一个名叫test.xsd的文件


3.输入命令 xjc D:\xsdTest\test.xsd  -d D:\xsdTest\ -p com.test,之后在目标目录生成一个目录,目录结构为/com/test会为你创建好,在test目录下会生成一个名叫TestList.java的文件和一个ObjectFactory.java文件,这个TestList文件就是我们xml模板所对应的javabean,内容和文章一开始的javabean一模一样





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值