JAXBをちょっと試してみました

今更ですが、JAXBを使って、XMLファイルを作成。ちょっとメモメモ。
通貨の情報はISO4217を参考にしました。

  • 作成したXMLファイル
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CcyTbl>
    <CcyNtry>
        <CtryNm>JAPAN</CtryNm>
        <CcyNm>YEN</CcyNm>
        <Ccy>JPY</Ccy>
        <CcyNbr>392</CcyNbr>
        <CcyMnrUnts>0</CcyMnrUnts>
    </CcyNtry>
    <CcyNtry>
        <CtryNm>UNITED STATES</CtryNm>
        <CcyNm>US Dollar</CcyNm>
        <Ccy>USD</Ccy>
        <CcyNbr>840</CcyNbr>
        <CcyMnrUnts>2</CcyMnrUnts>
    </CcyNtry>
</CcyTbl>
  • XML to Objectの結果

  • code1(Currency.java)

@XmlTypeアノテーションXML作成時のElementの順番を指定
@XmlElementアノテーションで、作成時のnameを指定

@XmlType(propOrder={"countryName", "name", "code", "numericCode", "minorUnit"})
public class Currency {
    private String code;
    private int numericCode;
    private String name;
    private String countryName;
    private int minorUnit;

    public String getCode() {
        return code;
    }
    @XmlElement(name="Ccy")
    public void setCode(String code) {
        this.code = code;
    }

    @XmlElement(name="CcyNbr")
    public int getNumericCode() {
        return numericCode;
    }

    public void setNumericCode(int NumericCode) {
        this.numericCode = NumericCode;
    }

    @XmlElement(name="CcyNm")
    public String getName() {
        return name;
    }

    public void setName(String Name) {
        this.name = Name;
    }

    @XmlElement(name="CtryNm")
    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @XmlElement(name="CcyMnrUnts")
    public int getMinorUnit() {
        return minorUnit;
    }

    public void setMinorUnit(int minorUnit) {
        this.minorUnit = minorUnit;
    }

    public static Currency createJPY() {
        Currency currency = new Currency();
        currency.setCode("JPY");
        currency.setName("YEN");
        currency.setCountryName("JAPAN");
        currency.setNumericCode(392);
        currency.setMinorUnit(0);
        return currency;
    }

    public static Currency createUSD() {
        Currency currency = new Currency();
        currency.setCode("USD");
        currency.setName("US Dollar");
        currency.setCountryName("UNITED STATES");
        currency.setNumericCode(840);
        currency.setMinorUnit(2);
        return currency;
    }
 
    public String getCurrecyData(){
        return String.format("Code:%s, Name:%s, Country:%s, Numeric Code:%d, Minor Unit:%d"
                , code, name,countryName, numericCode, minorUnit);
    }
}
  • code2(Currencies.java)

複数のCurrencyクラスをxml出力したいので、ここでリストとして作成、
code3で、実際にxmlファイルを作成するクラスとしてこの「Currencies」を使用

@XmlRootElement(name="CcyTbl")
    @XmlAccessorType(XmlAccessType.FIELD)
public class Currencies {
    @XmlElement(name="CcyNtry")
    private List<Currency> currencies;

    public List<Currency> getCurrencies() {
        return currencies;
    }

    public void setCurrencies(List<Currency> currencies) {
        this.currencies = currencies;
    }
    
}
  • code3(JaxbSample.java)

1.円とドルのCurrencyクラスを作成CurrenciesクラスのCurrencyリストに設定
2.Marshallerクラスのmarshalメソッドxmlファイル作成
3.作成した、xmlファイルを読込み、UnmashallerクラスのunmarshlメソッドでObjectに変換
4.Currencyクラスに設定されている値を出力

public class JaxbSample {

    public static void main(String[] args) throws Exception {
        JaxbSample sample = new JaxbSample();
        Path xmlPath = Paths.get("/Users/tomo/currency.xml");
        sample.ObjToXml(xmlPath);
        sample.XmlToObj(xmlPath);
    }

    private void ObjToXml(Path xmlPath) throws Exception {
        List<Currency> currencyList = Arrays.asList(
              Currency.createJPY()
            , Currency.createUSD()
        );
        Currencies currencies = new Currencies();
        currencies.setCurrencies(currencyList);      // *** 1 ***
        JAXBContext context = JAXBContext.newInstance(Currencies.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        try (BufferedWriter writer = Files.newBufferedWriter(xmlPath)){
            marshaller.marshal(currencies, writer);    // *** 2 ***
        }
    }

    private void XmlToObj(Path xmlPath) throws Exception{
        JAXBContext context = JAXBContext.newInstance(Currencies.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        try (BufferedReader reader = Files.newBufferedReader(xmlPath);) {
            Currencies unmarshal = (Currencies) unmarshaller.unmarshal(reader);   // *** 3 ***
            unmarshal.getCurrencies().forEach(c -> {
                System.out.println(c.getCurrecyData());   // *** 4 ***
            });
        }
    }
}

コードはtomoTaka01/XmlSample - Java - GitHubにupしました。
次は「StAX」で同じことに挑戦!