SpringのObject/XML Mappingは、ObjectをXMLまたはその逆に変換しています。このプロセスは、


  1. XML Marshalling

    – オブジェクトをXMLに変換します.


  2. XML UnMarshalling

    – XMLをオブジェクトに変換します.

このチュートリアルでは、Springのoxmを使用して

Object XML

変換を行う方法を説明します。

1.プロジェクトの依存関係

この例の依存関係

  • 注意** Springのoxm自体は、XMLマーシャリングやUnMarshallingを処理しません。開発者はXMLバインディングフレームワークを優先して注入する必要があります。この場合、Castorバインディングフレームワークを使用します。

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring oxm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Uses Castor for XML -->
        <dependency>
            <groupId>org.codehaus.castor</groupId>
            <artifactId>castor</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Castor need this -->
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.1</version>
        </dependency>

    </dependencies>

2.シンプルなオブジェクト

単純なオブジェクトは、後でそれをXMLファイルに変換します。

package com.mkyong.core.model;

public class Customer {

    String name;
    int age;
    boolean flag;
    String address;

   //standard getter, setter and toString() methods.
}

3. MarshallerとUnmarshaller

このクラスは、Springのoxmインタフェースによる変換を処理します:

`マーシャル ‘と`アンマーシャラー’。

package com.mkyong.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter {

    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public Marshaller getMarshaller() {
        return marshaller;
    }

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public Unmarshaller getUnmarshaller() {
        return unmarshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }

    public void convertFromObjectToXML(Object object, String filepath)
        throws IOException {

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filepath);
            getMarshaller().marshal(object, new StreamResult(os));
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    public Object convertFromXMLToObject(String xmlfile) throws IOException {

        FileInputStream is = null;
        try {
            is = new FileInputStream(xmlfile);
            return getUnmarshaller().unmarshal(new StreamSource(is));
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

}

4.春の設定

SpringのBean設定ファイルで、XMLバインディングフレームワークとして `CastorMarshaller`を挿入します。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="XMLConverter" class="com.mkyong.core.XMLConverter">
        <property name="marshaller" ref="castorMarshaller"/>
        <property name="unmarshaller" ref="castorMarshaller"/>
    </bean>
    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>

</beans>

5.テスト

それを実行します。

package com.mkyong.core;

import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.core.model.Customer;

public class App {
    private static final String XML__FILE__NAME = "customer.xml";

    public static void main(String[]args) throws IOException {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("App.xml");
        XMLConverter converter = (XMLConverter) appContext.getBean("XMLConverter");

        Customer customer = new Customer();
        customer.setName("mkyong");
        customer.setAge(30);
        customer.setFlag(true);
        customer.setAddress("This is address");

        System.out.println("Convert Object to XML!");
       //from object to XML file
        converter.convertFromObjectToXML(customer, XML__FILE__NAME);
        System.out.println("Done \n");

        System.out.println("Convert XML back to Object!");
       //from XML to object
        Customer customer2 = (Customer)converter.convertFromXMLToObject(XML__FILE__NAME);
        System.out.println(customer2);
        System.out.println("Done");

    }
}

出力

Convert Object to XML!
Done

Convert XML back to Object!
Customer[name=mkyong, age=30, flag=true, address=This is address]Done

以下のXMLファイル ”

customer.xml

“がプロジェクトのルートフォルダに生成されます。


File:customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer flag="true" age="30">
    <address>This is address</address>
    <name>mkyong</name>
</customer>

Castor XMLマッピング

なぜ、フラグと年齢が属性として変換されるのでしょうか?これは、属性や要素として使用するフィールドを制御する方法ですか?もちろん、http://www.castor.org/xml-mapping.html%20target=[Castor XMLマッピング]を使用して、オブジェクトとXMLの関係を定義することができます。

次のマッピングファイルを作成し、プロジェクトのクラスパスに配置します。


File:mapping.xml

<mapping>
    <class name="com.mkyong.core.model.Customer">

        <map-to xml="customer"/>

        <field name="age" type="integer">
            <bind-xml name="age" node="attribute"/>
        </field>

        <field name="flag" type="boolean">
            <bind-xml name="flag" node="element"/>
        </field>

        <field name="name" type="string">
            <bind-xml name="name" node="element"/>
        </field>

        <field name="address" type="string">
            <bind-xml name="address" node="element"/>
        </field>
    </class>
</mapping>

Spring bean設定ファイルで、

mapping.xml

をCastorMarshallerの上に ”

mappingLocation

“を介して挿入します。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="XMLConverter" class="com.mkyong.core.XMLConverter">
        <property name="marshaller" ref="castorMarshaller"/>
        <property name="unmarshaller" ref="castorMarshaller"/>
    </bean>
    <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" >
        <property name="mappingLocation" value="classpath:mapping.xml"/>
    </bean>

</beans>

再度テストすると、XMLファイル ”

customer.xml

“が更新されます。


File:customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer age="30">
    <flag>true</flag>
    <name>mkyong</name>
    <address>This is address</address>
</customer>

ソースコードをダウンロードする

ダウンロードする –

Spring3-Object-XML-Mapping-Example.zip

(7 KB)