JAXB教程–入门
注意:請查看我們的Java XML綁定JAXB教程– ULTIMATE指南
什么是JAXB?
JAXB代表用于XML綁定的Java體系結構。它用于將XML轉換為java對象,并將java對象轉換為XML。JAXB定義了一個用于在XML文檔中讀寫Java對象的API。與SAX和DOM不同,我們不需要了解XML解析技術。
您可以使用JAXB執行兩種操作
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;}@XmlElementpublic void setCountryName(String countryName) {this.countryName = countryName;}public double getCountryPopulation() {return countryPopulation;}@XmlElementpublic 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 objectCountry countryIndia=new Country(); countryIndia.setCountryName('India');countryIndia.setCountryPopulation(5000000);// Creating listOfStatesArrayList<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 MarshallerJAXBContext jaxbContext = JAXBContext.newInstance(Country.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();// for getting nice formatted outputjaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);//specify the location and name of xml file to be createdFile XMLfile = new File('C:\\arpit\\CountryRecord.xml');// Writing to XML filejaxbMarshaller.marshal(countryIndia, XMLfile); // Writing to consolejaxbMarshaller.marshal(countryIndia, System.out); } catch (JAXBException e) {// some exception occurede.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 MarshallerJAXBContext jaxbContext = JAXBContext.newInstance(Country.class);Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();// specify the location and name of xml file to be readFile XMLfile = new File('C:\\arpit\\CountryRecord.xml');// this will create Java object - country from the XML fileCountry 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 occurede.printStackTrace();}} }運行以上程序后,將得到以下輸出:
控制臺輸出:
Country Name: India Country Population: 5000000.0 State:1 Madhya Pradesh State:2 MaharastraJAXB的優點:
- 它比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
總結
- 上一篇: Hadoop赠品–综述
- 下一篇: 2000元音箱加电脑(2000元左右电脑