码迷,mamicode.com
首页 > 其他好文 > 详细

JAXB使用小结

时间:2019-04-08 13:08:48      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:sax   com   ring   span   sys   repo   str   string   param   

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使用小结

标签:sax   com   ring   span   sys   repo   str   string   param   

原文地址:https://www.cnblogs.com/liulihaha/p/10669640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!