JAXB教程

时间:2020-02-23 14:35:17  来源:igfitidea点击:

什么是JAXB?

JAXB代表XML绑定的Java架构。
它用于将XML转换为Java对象,Java对象到XML.JAXB定义了用于读取和从XML文档中读取和写入Java对象的API.UNLIKE SAX和DOM,我们不需要要意识到XML解析技术。

我们可以使用JAXB执行两个操作

  • 编组:将Java对象转换为XML
  • Unmarshalling:将XML转换为Java对象

JAXB教程

我们将创建一个Java程序到Marshal和Unmarshal。

用于编组:

对于解释:

Java程序:

借助JAXB提供的注释和API,将Java对象转换为XML,反之亦然变得非常容易。

1.Country.java.

一个Java对象将用于转换往返XML

在src-> org.igi.javapostssforlearning.jaxb中创建country.java.javapostsforlearning.jaxb

package org.igi.javapostsforlearning.jaxb;
 
import java.util.ArrayList;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
 
//Below annotation defines root element of XML file
@XmlRootElement
//You can define order in which elements will be created in XML file
//Optional
@XmlType(propOrder = { "countryName", "countryPopulation", "listOfStates"})
public class Country {
 
	private String countryName;
	private double countryPopulation;
 
	private ArrayList<State> listOfStates;
	public Country() {
 
	}
	public String getCountryName() {
		return countryName;
	}
	@XmlElement
	public void setCountryName(String countryName) {
		this.countryName = countryName;
	}
	public double getCountryPopulation() {
		return countryPopulation;
	}
 
	@XmlElement
	public void setCountryPopulation(double countryPopulation) {
		this.countryPopulation = countryPopulation;
	}
 
 
	public ArrayList<State> getListOfStates() {
		return listOfStates;
	}
 
	//XmLElementWrapper generates a wrapper element around XML representation
	@XmlElementWrapper(name = "stateList")
	//XmlElement sets the name of the entities in collection
	@XmlElement(name = "state")
	public void setListOfStates(ArrayList<State> listOfStates) {
		this.listOfStates = listOfStates;
	}
 
}< /pre>

@xmlrootelement:此注释定义了XML文件的根元素。
@xmltype(proporder = {"属性列表"}):这用于定义XML文件中的元素顺序。
这是可选的。
@XmlElement:这用于定义XML文件中的元素。
它的实体名称。
@xmlelementwrapper(name ="名称要提供给该包装器"):它会在XML表示周围生成一个包装元素。
在上面的示例中,它将生成每个元素

2.State.java.

package org.igi.javapostsforlearning.jaxb;
 
import javax.xml.bind.annotation.XmlRootElement;
 
//Below statement means that class "Country.java" is the root-element of our example
@XmlRootElement(namespace = "org.igi.javapostsforlearning.jaxb.Country")
public class State {
 
 
	private String stateName;
	long statePopulation;
 
	public State()
	{
 
	}
	public State(String stateName, long statePopulation) {
		super();
		this.stateName = stateName;
		this.statePopulation = statePopulation;
	}
 
	public String getStateName() {
		return stateName;
	}
 
	public void setStateName(String stateName) {
		this.stateName = stateName;
	}
 
	public long getStatePopulation() {
		return statePopulation;
	}
 
	public void setStatePopulation(long statePopulation) {
		this.statePopulation = statePopulation;
	}
}

3.jaxbavatoxml.java.

package org.igi.javapostsforlearning.jaxb;
 
import java.io.File;
import java.util.ArrayList;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
 
public class JAXBJavaToXml {
	public static void main(String[] args) {
 
		//creating country object
		Country countryNetherlands=new Country();  
		countryNetherlands.setCountryName("Netherlands");
		countryNetherlands.setCountryPopulation(5000000);
 
		//Creating listOfStates
		ArrayList<State> stateList=new ArrayList<State>();
		State mpState=new State("Madhya Pradesh",1000000);
		stateList.add(mpState);
		State maharastraState=new State("Maharastra",2000000);
		stateList.add(maharastraState);
 
		countryNetherlands.setListOfStates(stateList);
 
		try {
 
			//create JAXB context and initializing Marshaller
			JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
			//for getting nice formatted output
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
 
			//specify the location and name of xml file to be created
			File XMLfile = new File("C:\igi\CountryRecord.xml");
 
			//Writing to XML file
			jaxbMarshaller.marshal(countryNetherlands, XMLfile); 
			//Writing to console
			jaxbMarshaller.marshal(countryNetherlands, System.out); 
 
		} catch (JAXBException e) {
			//some exception occured
			e.printStackTrace();
		}
 
	}
}

在运行上面的程序后,我们将获得以下输出

控制台输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<country xmlns:ns2="org.igi.javapostsforlearning.jaxb.Country">
    <countryName>Netherlands</countryName>
    <countryPopulation>5000000.0</countryPopulation>
    <stateList>
        <state>
            <stateName>Madhya Pradesh</stateName>
            <statePopulation>1000000</statePopulation>
        </state>
        <state>
            <stateName>Maharastra</stateName>
            <statePopulation>2000000</statePopulation>
        </state>
    </stateList>
</country>

现在我们将阅读以上生成的XML并从中检索Country对象。

4.jaxbxmltojava.java.

package org.igi.javapostsforlearning.jaxb;
 
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class JAXBXMLToJava {
	public static void main(String[] args) {
 
		try {
 
			//create JAXB context and initializing Marshaller
			JAXBContext jaxbContext = JAXBContext.newInstance(Country.class);
 
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 
			//specify the location and name of xml file to be read
			File XMLfile = new File("C:\igi\CountryRecord.xml");
 
			//this will create Java object - country from the XML file
			Country countryNetherlands = (Country) jaxbUnmarshaller.unmarshal(XMLfile);
 
			System.out.println("Country Name: "+countryNetherlands.getCountryName());
			System.out.println("Country Population: "+countryNetherlands.getCountryPopulation());
 
			ArrayList<State> listOfStates=countryNetherlands.getListOfStates();
 
			int i=0; 
			for(State state:listOfStates)
			{
				i++;
				System.out.println("State:"+i+" "+state.getStateName());
			}
 
		} catch (JAXBException e) {
			//some exception occured
			e.printStackTrace();
		}
 
	}
}

在运行上面的程序后,我们将获得以下输出

控制台输出:

Country Name: Netherlands
Country Population: 5000000.0
State:1 Madhya Pradesh
State:2 Maharastra

JAXB优点:

  • 它比DOM或者SAX解析器使用非常简单
  • 我们可以将XML文件汇编到InputStream,URL,DOM节点等其他数据目标。
  • 我们可以从其他数据目标中解离XML文件。
  • 我们不需要意识到XML解析技术。
  • 我们始终不需要在树结构中访问XML。

JAXB缺点:

  • JAXB是高层API,因此对解析的控制较少,而不是SAX或者DOM。
  • 它有一些开销任务,因此它比萨克斯慢。