JAXB使用小结

Posted liulihaha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAXB使用小结相关的知识,希望对你有一定的参考价值。

Object转XML,XML转Object

一、引入依赖(各种json框架都可以)

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

二、创建对象实体

package entity;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="demo")
//element的顺序
@XmlType(propOrder={"twoString","oneString"})
//表示使用getter/setter注入属性
@XmlAccessorType(XmlAccessType.FIELD)
public class Demo {
    
    @XmlElement(name="oneString",required=true)
    private String oneString;
    
    @XmlElement(name="twoString",required=true)
    private String twoString;

    public String getOneString() {
        return oneString;
    }

    public void setOneString(String oneString) {
        this.oneString = oneString;
    }

    public String getTwoString() {
        return twoString;
    }

    public void setTwoString(String twoString) {
        this.twoString = twoString;
    }

    @Override
    public String toString() {
        return "Demo [oneString=" + oneString + ", twoString=" + twoString
                + "]";
    }

}

三、创建xsd校验

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="demo">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="twoString"></xs:element>
                <xs:element name="oneString"></xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

四、测试

package util;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;

import entity.Demo;

public class JAXBUtil {
    
    /**
     * 对象转xml
     * @param obj
     * @return
     * @throws JAXBException
     * @throws SAXException
     */
    public static String objToXml(Object obj) throws JAXBException, SAXException{
        StringWriter sw = new StringWriter();
        JAXBContext jAXBContext = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = jAXBContext.createMarshaller();
        //格式化输出
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //加入xsd验证
        marshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File("src\main\webapp\demo.xsd")));
        //输出对象为文件
        marshaller.marshal(obj, new File("C:\Users\mayn\Desktop\test.xml"));
        //输出对象为字符串
        marshaller.marshal(obj, sw);
        //控制台输出对象
        marshaller.marshal(obj, System.out);
        System.out.println("-------------------------------------------");
        return sw.toString();
    }
    
    /**
     * xml转对象
     * @param file xml文件
     * @param c
     * @return
     * @throws JAXBException
     * @throws SAXException 
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToObj(File file,String xml,Class<T> c) throws JAXBException, SAXException{
        JAXBContext context = JAXBContext.newInstance(c);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        //加入xsd校验
        unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File("src\main\webapp\demo.xsd")));
        //解析文件或xml字符串为对象
        T t = null;
        t = (T)(file != null ? unmarshaller.unmarshal(file) : unmarshaller.unmarshal(new StreamSource(new StringReader(xml))));
        return t;
    }
    
    public static void main(String[] args) throws JAXBException, SAXException {
        Demo demo = new Demo();
        demo.setOneString("testOne");
        demo.setTwoString("testTwo");
        String str = objToXml(demo);
        System.out.println(str);
        System.out.println(xmlToObj(new File("C:\Users\mayn\Desktop\test.xml"),null, Demo.class));
        System.out.println(xmlToObj(null, str, Demo.class));
    }

}

控制台输出情况

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<demo>
    <twoString>testTwo</twoString>
    <oneString>testOne</oneString>
</demo>
-------------------------------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<demo>
    <twoString>testTwo</twoString>
    <oneString>testOne</oneString>
</demo>

Demo [oneString=testOne, twoString=testTwo]
Demo [oneString=testOne, twoString=testTwo]

测试文件test.xml内容

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<demo>
    <twoString>testTwo</twoString>
    <oneString>testOne</oneString>
</demo>

 

以上是关于JAXB使用小结的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JAXB 生成 CDATA 块?

如何在 Jaxb 中进行数字签名

Jaxb 2.0 Schema 验证问题

如何配置 IntelliJ IDEA 和/或 Maven 以使用 jaxb2-maven-plugin 生成的 Java 源代码自动添加目录?

使用 JAXB 获取 XML 子节点的值

如何获取JAXB对象的命名空间