XML与Java转换之JAXB

本文详细介绍了JAXB(Java Architecture for XML Binding)技术,包括其基本概念、定位及与其他解析技术的对比。重点讲解了如何使用JAXB进行XML到JavaBean的转换,包括从XML生成XSD,从XSD生成Java类,以及如何将XML字符串转换为Java对象,反之亦然。同时,提供了具体代码示例,展示了JavaBean到XML的转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、JAXB介绍

 

    1、JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema(.xsd文件)产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到 XML实例文档。

    2、基本概念

        a、JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。

        b、Marshaller接口,将Java对象序列化为XML数据。          【schemagen】

        c、Unmarshaller接口,将XML数据反序列化为Java对象。   【xjc】

    3、JAXB定位

        a、解析速度对比:SAX > DOM4J > JAXB > JDOM > DOM

        b、解析内存对比: SAX < DOM4J < JAXB < JDOM < DOM

        c、编程复杂对比:JAXB <DOM4J <JDOM <DOM < SAX

    4、转换关系

       

 

二、xml--->JavaBean过程

    1、将xml转换成xsd

        a、工具:Altova XMLSpy

        b、用Altova XMLSpy打开xml文件--->DTD/模式--->产生DTD/模式--->确定

    2、将xsd转换成对象

        a、工具:eclipse

        b、右键xsd文件--->Generate--->JXAB Classes

    3、将xml文件转换成String

        a、方式一

 

private String readXmlFromFile(String fileName) {
InputStream in = ClassLoader.getSystemResourceAsStream(fileName+ ".xml");
String xml = "";
try {
xml = IOUtils.toString(in, Charsets.toCharset(Charset.defaultCharset()));
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}

        b、方式二

 

private  String xmlToString(String fileName)  throws Exception{
final URL url = ClassLoader.getSystemResource(fileName);
String xml = FileUtils.readFileToString(new File(URLDecoder.decode(
url.getPath(), "UTF-8")));
return xml;
}

    3、将String装换成对象

        a、方式一(最大元素.class)

 

package service;

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class XmlParserService {

private static JAXBContext context = null;
private static final Object OBJECT = new Object();
/**
* Description: xml转换成JavaBean对象
* @param xml xml字符串
* @param c Class
* @return xml转换成的泛型对象
* @throws JAXBException JAXBException
* @throws XMLStreamException XMLStreamException
*/
@SuppressWarnings("unchecked")
public static <T> T converyToJavaBean(String xml, Class<T> c) throws JAXBException, XMLStreamException {
buildJAXBContext(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
XMLInputFactory xif = XMLInputFactory.newFactory();  
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);  
                xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);  
                xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);    
                XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));  
return (T) unmarshaller.unmarshal(xsr);
}

/**

* <p>Title: buildJAXBContext </p>
* <p>Description: 创建JAXBContext对象 </p>
* @param c class
* @param <T>  t
* @throws JAXBException JAXBException
*/
private static <T> void buildJAXBContext(Class<T> c) throws JAXBException{
if(null == context){
synchronized (OBJECT) {
if(null == context){
context = JAXBContext.newInstance(c);//xml中最大的元素
}
}
}
}

}

        b、方式二(包路径)

 

 

package service;


import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class XmlParserService {

private static JAXBContext context = null;
private static final Object OBJECT = new Object();
/**
* Description: xml转换成JavaBean对象
* @param xml xml字符串
* @param c Class
* @return xml转换成的泛型对象
* @throws JAXBException JAXBException
* @throws XMLStreamException XMLStreamException
*/
@SuppressWarnings("unchecked")
public static <T> T converyToJavaBean(String xml, String path) throws JAXBException, XMLStreamException {
buildJAXBContext(path);
Unmarshaller unmarshaller = context.createUnmarshaller();//解组:xml--->bean
XMLInputFactory xif = XMLInputFactory.newFactory();  
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);  
                xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);  
                xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);    
                XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));  
return (T) unmarshaller.unmarshal(xsr);
}

/**

* <p>Title: buildJAXBContext </p>
* <p>Description: 创建JAXBContext对象 </p>
* @param c class
* @param <T>  t
* @throws JAXBException JAXBException
*/
private static <T> void buildJAXBContext(String path) throws JAXBException{
if(null == context){
synchronized (OBJECT) {
if(null == context){
context = JAXBContext.newInstance(path);//path为包名
}
}
}
}
}

 

三、Java--->xml过程

 

package service;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;


public class XmlParserService {

private static JAXBContext context = null;
private static final Object OBJECT = new Object();

/**
* Description: JavaBean转换成xml, 默认编码UTF-8
* @param obj JavaBean对象
* @return JavaBean对象转换成XML的字符串
* @throws JAXBException JAXBException
*/
public static String convertToXml(Object obj) throws JAXBException {
return convertToXml(obj, "UTF-8");
}

/**
* Description: JavaBean转换成xml
* @param obj Java对象
* @param encoding 编码格式
* @return Java对象转换成的XML字符串
* @throws JAXBException JAXBException
*/
public static String convertToXml(Object obj, String encoding) throws JAXBException{
buildJAXBContext(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);
return writer.toString();
}

/**

* <p>Title: buildJAXBContext </p>
* <p>Description: 创建JAXBContext对象 </p>
* @param c class
* @param <T>  t
* @throws JAXBException JAXBException
*/
private static <T> void buildJAXBContext(Class<T> c) throws JAXBException{
if(null == context){
synchronized (OBJECT) {
if(null == context){
context = JAXBContext.newInstance(c);//xml中最大的元素
}
}
}
}

}

 

四、先关知识

1、xsd--->JavaBean

     <xsd:attribute>、</xsd:element></xsd:simpleType>将会被转换为属性

     </xsd:element></xsd:complexType>将会被转换为对象

2、xml schema(xsd文档)与xml文档的关系:XML和Schema命名空间详解---实例

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值