JAXB是 用于XML綁定的Java體系結(jié)構(gòu)的首字母縮寫(xiě)。它允許Java開(kāi)發(fā)人員將Java類(lèi)映射為XML表示形式。 JAXB可用于將Java對(duì)象編組為XML,反之亦然。
它是Sun提供的OXM(對(duì)象XML映射)或O/M框架。
JAXB的優(yōu)勢(shì)無(wú)需創(chuàng)建或使用SAX或DOM解析器,也無(wú)需編寫(xiě)回調(diào)方法。
您需要為創(chuàng)建以下文件使用帶有JAXB的Spring將Java對(duì)象編組為XML:
Employee.java applicationContext.xml Client.java
要運(yùn)行此示例,您需要加載:
Spring Core jar文件 Spring Web jar文件
下載spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting ,oxm,jdbc,orm等。
Employee.java
如果定義了三個(gè)屬性id,名稱(chēng)和薪水。我們?cè)诖祟?lèi)中使用了以下注釋:
@XmlRootElement 它指定xml文件的根元素。 @XmlAttribute 它指定屬性的屬性。 @XmlElement 它指定元素。
package com.nhooo; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="employee") public class Employee { private int id; private String name; private float salary; @XmlAttribute(name="id") public int getId() { return id; } public void setId(int id) { this.id = id; } @XmlElement(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name="salary") public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } }
applicationContext.xml
它定義了一個(gè)Bean jaxbMarshallerBean,其中Employee類(lèi)與OXM框架綁定。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <oxm:jaxb2-marshaller id="jaxbMarshallerBean"> <oxm:class-to-be-bound name="com.nhooo.Employee"/> </oxm:jaxb2-marshaller> </beans>
Client.java
它從applicationContext.xml文件獲取Marshaller的實(shí)例并調(diào)用marshal方法。
package com.nhooo; import java.io.FileWriter; import java.io.IOException; import javax.xml.transform.stream.StreamResult; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.oxm.Marshaller; public class Client{ public static void main(String[] args)throws IOException{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean"); Employee employee=new Employee(); employee.setId(101); employee.setName("Sonoo Jaiswal"); employee.setSalary(100000); marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml"))); System.out.println("XML Created Sucessfully"); } }
employee.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee id="101"> <name>Sonoo Jaiswal</name> <salary>100000.0</salary> </employee>