Jaxb实现Java对象与XML之间的转换

本文介绍了一种使用JAXB实现XML与Java对象互相转换的方法,并提供了具体代码实例及测试运行过程。通过该方法可以方便地进行XML配置文件的读取与生成。

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

Jaxb核心代码:

package ie.swing.xml.parse;

import ie.swing.xml.model.Components;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;

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

/**
 * 组件配置文件解析
 * 
 * @author lile
 * 
 */
public class ComponentAnalysis {
	
	/**
		根据schema文件生成Java类的命令:
				xjc.bat -classpath . ie/swing/config/component-1.0.xsd
	 */
	
	/**
	 * XML to Java
	 * @param packageName 包名, 如 ie.swing.xml.model
	 * @param xmlPath 要解析的xml文件路径 如 "src/ie/swing/config/component.xml"
	 * @return rootObject 根对象
	 * @throws JAXBException
	 * @throws FileNotFoundException
	 */
	public <T> T xml2Java(String packageName, String xmlPath) throws JAXBException, FileNotFoundException {
		JAXBContext context = JAXBContext.newInstance(packageName);   
        Unmarshaller unmarshaller = context.createUnmarshaller();   
        File file = new File(xmlPath);   
        @SuppressWarnings("unchecked")
		JAXBElement<T> rootElement = (JAXBElement<T>) unmarshaller.unmarshal(file);   
        T rootObject = rootElement.getValue();
        return rootObject;
	}
	
	/**
	 * Java to XML
	 * @param rootObject 根对象, Xml 根标签对应的对象
	 * @param out 输出流,该方法将xml数据写入该输出流
	 * @throws JAXBException
	 */
	public <T> void java2XML(T rootObject, OutputStream out) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(rootObject.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); // 编码格式
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 是否格式化生成的xml串
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); // 是否省略xml头信息
		marshaller.marshal(rootObject, out);
	}
	
	/**
	 * 测试运行
	 * @param args
	 * @throws FileNotFoundException
	 * @throws JAXBException
	 */
	public static void main(String[] args) throws FileNotFoundException, JAXBException {
		ComponentAnalysis ca = new ComponentAnalysis();
		//将Xml解析成Java对象
		Components cps = ca.xml2Java("ie.swing.xml.model", "src/ie/swing/config/component.xml");
		//将解析出的Java对象cps解析回Xml并输出到System.out
		ca.java2XML(cps, System.out);
	}
}


 

 

示例xsd schema文件 component-1.0.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
	targetNamespace="http://www.ie168.org/component-1.0" 
	xmlns:tns="http://www.ie168.org/component-1.0" 
	elementFormDefault="qualified">

    <element name="components" type="tns:components"></element>

    <complexType name="components">
    	<sequence>
    		<element ref="tns:component" maxOccurs="unbounded" minOccurs="1"></element>
    	</sequence>
    </complexType>
    
    <element name="component" type="tns:component"></element>
    
    <complexType name="component">
    	<sequence>
    		<element ref="tns:rectangle" maxOccurs="unbounded" minOccurs="0"></element>
    		<element ref="tns:ellipse" maxOccurs="unbounded" minOccurs="0"></element>
    	</sequence>
    	<attribute name="name" type="string"></attribute>
    	<attribute name="text" type="string"></attribute>
    </complexType>

    <element name="rectangle" type="tns:rectangle"></element>
    
    <complexType name="rectangle">
    	<attribute name="width" type="float"></attribute>
    	<attribute name="height" type="float"></attribute>
        <attributeGroup ref="tns:point"></attributeGroup>
    </complexType>

    <element name="ellipse" type="tns:ellipse"></element>
    
    <complexType name="ellipse">
    	<attribute name="startAngle" type="float"></attribute>
    	<attribute name="arcAngle" type="float"></attribute>
    	<attribute name="width" type="float"></attribute>
    	<attribute name="height" type="float"></attribute>
        <attributeGroup ref="tns:point"></attributeGroup>
    </complexType>
    
    <attributeGroup name="point">
    	<attribute name="x" type="float"></attribute>
    	<attribute name="y" type="float"></attribute>
    </attributeGroup>
</schema>


 

 

示例xml文件: component.xml

<?xml version="1.0" encoding="utf-8" ?>
<ie:components xmlns="http://www.w3.org/2001/XMLSchema"
			   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
               xmlns:ie="http://www.ie168.org/component-1.0"
               xsi:schemaLocation="http://www.ie168.org/component-1.0 component-1.0.xsd">
	<ie:component name="rectangle" text="矩形">
		<ie:rectangle height="100" width="100" x="0" y="0"/>
	</ie:component>
	
	<ie:component name="ellipse" text="椭圆">
		<ie:ellipse arcAngle="360" startAngle="0" height="100" width="100" x="0" y="0"/>
	</ie:component>
</ie:components>


 

运行之前先用JDK自带的命令:

    xjc.bat -classpath . 包名/component-1.0.xsd

根据schema文件生成对应的Java类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值