Exemple de mappage objet XML/XML

Exemple de mappage objet / XML Spring

Le mappage objet / XML de Spring convertit l'objet en XML ou vice versa. Ce processus est également appelé

  1. XML Marshalling - Convertit un objet en XML.

  2. XML UnMarshalling - Convertit XML en objet.

Dans ce didacticiel, nous vous montrons comment utiliser l'oxm de Spring pour effectuer la conversion,Object XML.

Note
Pas de bêtises, pour savoir pourquoi et quels avantages utiliser oxm de Spring, lisez cet article deofficial Spring Object/XML mapping.

1. Dépendance du projet

Dépendances dans cet exemple.

Note
L'oxm de Spring lui-même ne gère pas le marshalling XML ou UnMarshalling, cela dépend du développeur pour injecter son framework de liaison XML préféré. Dans ce cas, vous utiliserez le cadre de liaison Castor.

    
        3.0.5.RELEASE
    

    

        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-context
            ${spring.version}
        

        
        
            org.springframework
            spring-oxm
            ${spring.version}
        

        
        
            org.codehaus.castor
            castor
            1.2
        

        
        
            xerces
            xercesImpl
            2.8.1
        

    

2. Objet simple

Un objet simple, convertissez-le plus tard en fichier XML.

package com.example.core.model;

public class Customer {

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

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

3. Marshaller et Unmarshaller

Cette classe gérera la conversion via les interfaces oxm de Spring:Marshaller etUnmarshaller.

package com.example.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. Configuration du ressort

Dans le fichier de configuration du bean de Spring, injectezCastorMarshaller comme cadre de liaison XML.



    
        
        
    
    

5. Test

Exécuter.

package com.example.core;

import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.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("example");
        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");

    }
}

Sortie

Convert Object to XML!
Done

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

Le fichier XML suivant «customer.xml» est généré dans le dossier racine de votre projet.

Fichier: customer.xml



    
This is address
example

Mappage XML Castor

Attendez, pourquoi le drapeau et l'âge sont convertis en attribut? Est-ce une façon de contrôler le champ à utiliser comme attribut ou élément? Bien sûr, vous pouvez utiliserCastor XML mapping pour définir la relation entre Object et XML.

Créez le fichier de mappage suivant et placez-le dans le chemin de classe de votre projet.

Fichier: mapping.xml


    

        

        
            
        

        
            
        

        
            
        

        
            
        
    

Dans le fichier de configuration Spring bean, injectez au-dessus demapping.xml dans CastorMarshaller via «mappingLocation».



    
        
        
    
    
        
    

Testez à nouveau, le fichier XML «customer.xml» sera mis à jour.

Fichier: customer.xml



    true
    example
    
This is address

Télécharger le code source

Téléchargez-le -Spring3-Object-XML-Mapping-Example.zip (7 Ko)