注意:请查看我们的Java XML绑定JAXB教程– ULTIMATE指南
什么是JAXB?
JAXB代表用于XML绑定的Java体系结构。它用于将XML转换为java对象,并将java对象转换为XML。JAXB定义了一个用于在XML文档中读写Java对象的API。与SAX和DOM不同,我们不需要了解XML解析技术。
您可以使用JAXB执行两种操作
- 编组 :将Java对象转换为XML
- 编组 :将XML转换为Java对象
JAXB教程
我们将创建一个封送和封送的Java程序。
对于编组:
对于解组:
Java程序:
借助JAXB提供的注释和API,将Java对象转换为XML(反之亦然)变得非常容易。
1.国家/地区
一个Java对象,用于在XML之间进行转换
在src-> org.arpit.javapostsforlearning.jaxb中创建Country.java
package org.arpit.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;
}
}
@XmlRootElement:此批注定义XML文件的根元素。
@XmlType(propOrder = {'属性列表顺序'}) :用于定义XML文件中元素的顺序。这是可选的。
@XmlElement:用于定义XML文件中的元素,它设置实体名称。 @XmlElementWrapper(name ='要赋予该包装器的名称'):它围绕XML表示形式生成一个包装器元素。例如,在上面的示例中,它将生成<stateList> 每个<state>元素周围
2.状态库
package org.arpit.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.arpit.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.JAXBJavaToXml.java
package org.arpit.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 countryIndia=new Country();
countryIndia.setCountryName('India');
countryIndia.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);
countryIndia.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:\\arpit\\CountryRecord.xml');
// Writing to XML file
jaxbMarshaller.marshal(countryIndia, XMLfile);
// Writing to console
jaxbMarshaller.marshal(countryIndia, System.out);
} catch (JAXBException e) {
// some exception occured
e.printStackTrace();
}
}
}
运行以上程序后,将得到以下输出
控制台输出:
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<country xmlns:ns2='org.arpit.javapostsforlearning.jaxb.Country'>
<countryName>India</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并从中获取国家对象。
4.JAXBXMLToJava.java
package org.arpit.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:\\arpit\\CountryRecord.xml');
// this will create Java object - country from the XML file
Country countryIndia = (Country) jaxbUnmarshaller.unmarshal(XMLfile);
System.out.println('Country Name: '+countryIndia.getCountryName());
System.out.println('Country Population: '+countryIndia.getCountryPopulation());
ArrayList<state> listOfStates=countryIndia.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: India
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相比,它对解析的控制更少。
- 它有一些开销的任务,因此它比SAX慢。
源代码:
参考: JAXB教程–从我们的JCG合作伙伴 Arpit Mandliya 入门 , 了解有关初学者博客的Java框架和设计模式 。
翻译自: https://www.javacodegeeks.com/2013/02/jaxb-tutorial-getting-started.html