1. 程式人生 > >JAXB解析與生成XML

JAXB解析與生成XML

使用JAXB可以快速完成Java類到XML的對映,方便XML檔案的解析與生成。

常用註解

@XmlRootElement(name = "Country")
將Java類或列舉型別對映成XML中根元素,設定name屬性的值可指定義根元素名稱,不設定則預設為型別首字母小寫的名稱。

@XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
將Java類後列舉型別對映到XML模式型別,設定propOrder可以指定生成XML中各元素的先後順序。

@XmlElement(name = "CFoundationTime")
將JavaBean中的欄位值對映到XML元素,設定name屬性的值可指定XML元素的名稱。

@XmlAttribute
(name = "CRank", required = false)
將JavaBean中的欄位對映到XML中元素的屬性,設定name屬性的值可指定xml中元素屬性的名稱;
至於required屬性,官方文件是說指定 XML 模式屬性是可選的還是必需的,不是特別理解。

@XmlElementWrapper(name = "CountryWrapper")
為集合生成xml包裝器元素,簡單來講就是使XML元素更有層次感,更美觀,該註解只能用在集合上。

例子

1、類結構如下

Country與Countries為對映物件;
JAXBUtils提供讀寫XML的方法;
JAXBXMLTest提供讀寫測試方法;

2、各個類如下

Country類:

package com.jaxb;

import javax.xml.bind.annotation.*;

@XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
@XmlRootElement(name = "Country")
public class Country {
    private int population;
    private String name;
    private String capital;
    private int rank;
    private String foundationTime;

    public String getFoundationTime() {
        return foundationTime;
    }

    @XmlElement(name = "CFoundationTime")
    public void setFoundationTime(String foundationTime) {
        this.foundationTime = foundationTime;
    }

    public int getPopulation() {
        return population;
    }

    @XmlElement(name = "CPopulation")
    public void setPopulation(int population) {
        this.population = population;
    }

    public String getName() {
        return name;
    }

    @XmlElement(name = "CName")
    public void setName(String name) {
        this.name = name;
    }

    public String getCapital() {
        return capital;
    }

    @XmlElement(name = "CCapital")
    public void setCapital(String capital) {
        this.capital = capital;
    }

    public int getRank() {
        return rank;
    }

    @XmlAttribute(name = "CRank", required = true)
    public void setRank(int rank) {
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "Country=[Name=" + this.getName() +
                ", Capital=" + this.getCapital() +
                ", Population=" + this.getPopulation() +
                ", FoundationTime=" + this.getFoundationTime() + "]";
    }
}

Countries類:

package com.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement(name = "Countries")
public class Countries {
    private List<Country> countries;

    public List<Country> getCountries() {
        return countries;
    }

    @XmlElementWrapper(name = "CountryWrapper")
    @XmlElement(name = "Country")
    public void setCountries(List<Country> countries) {
        this.countries = countries;
    }

    @Override
    public String toString() {
        return "Countries=[" + this.getCountries() + "]";
    }
}

JAXBUtils類:

package com.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public class JAXBUtils {
    public static void writeXML(Object obj, File path, Class... clazz) throws JAXBException {
        JAXBContext jctx = JAXBContext.newInstance(clazz);
        Marshaller marshaller = jctx.createMarshaller();
        // 格式化輸出,設定換行和縮排,不設定則會顯示在一行
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(obj, path);
        // 設定控制檯輸出
        marshaller.marshal(obj, System.out);
    }

    public static Object readXML(File path, Class... clazz) throws JAXBException {
        JAXBContext jctx = JAXBContext.newInstance(clazz);
        Unmarshaller unMarshaller = jctx.createUnmarshaller();
        Object obj = unMarshaller.unmarshal(path);

        return obj;
    }
}

JAXBXMLTest類:

package com.jaxb;

import javax.xml.bind.JAXBException;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;

public class JAXBXMLTest {
    private static final String XML_PATH_COUNTRY = "./Country.xml";
    private static final String XML_PATH_COUNTRIES = "./Countries.xml";

    public static void main(String[] args) throws JAXBException {
        Country china = new Country();
        china.setName("中國");
        china.setCapital("北京");
        china.setPopulation(1400000000);
        china.setRank(25);
        String fTimeChina = LocalDate.of(1949, 10, 1).toString();
        china.setFoundationTime(fTimeChina);

        Country america = new Country();
        america.setName("United States of America");
        america.setCapital("New York");
        america.setPopulation(300000000);
        america.setRank(11);
        String fTimeAmerica = LocalDate.of(1776, 7, 4).toString();
        america.setFoundationTime(fTimeAmerica);

        File xmlFile = new File(XML_PATH_COUNTRY);
        File xmlFile1 = new File(XML_PATH_COUNTRIES);

        System.out.println("\n【寫入到" + XML_PATH_COUNTRY + "】");
        JAXBUtils.writeXML(china, xmlFile, Country.class);

        System.out.println("\n【寫入list到" + XML_PATH_COUNTRIES + "】");
        Countries countries = new Countries();
        ArrayList<Country> list = new ArrayList<>();
        list.add(china);
        list.add(america);
        countries.setCountries(list);
        JAXBUtils.writeXML(countries, xmlFile1, Countries.class);

        System.out.println("\n【從" + XML_PATH_COUNTRIES + "中讀取】");
        Countries countriesRead = (Countries) JAXBUtils.readXML(xmlFile1, Countries.class, Country.class);
        System.out.println(countriesRead);

        System.out.println("\n【從" + XML_PATH_COUNTRY + "中讀取】");
        Country countryRead = (Country) JAXBUtils.readXML(xmlFile, Country.class);
        System.out.println(countryRead);
    }
}

執行測試類,結果如下: