Как использовать spring для маршалинга и unmarshal xml?

у меня есть проект spring boot. У меня есть несколько xsds в моем проекте. Я создал классы с помощью Maven-jaxb2-plugin. Я использовал этой учебник, чтобы получить пример запуска приложения spring boot.

import org.kaushik.xsds.XOBJECT;

@SpringBootApplication
public class JaxbExample2Application {

public static void main(String[] args) {
    //SpringApplication.run(JaxbExample2Application.class, args);
    XOBJECT xObject = new XOBJECT('a',1,2);

    try {
        JAXBContext jc = JAXBContext.newInstance(User.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(xObject, System.out);

    } catch (PropertyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }
}

но меня беспокоит то, что мне нужно сопоставить все классы jaxb схемы. Также есть что-то весной, что я могу использовать, чтобы облегчить свою задачу. Я смотрел на родник сайт oxm проект, но он имел контекст приложения настроен в формате xml. У spring boot есть что-нибудь, что я могу использовать из коробки. Любые примеры будут полезны.

редактировать

пробовал xerx593 это и я провел простой тест, используя main method

    JaxbHelper jaxbHelper = new JaxbHelper();
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(XOBJECT.class);
    jaxbHelper.setMarshaller(marshaller);
    XOBJECT xOBJECT= (PurchaseOrder)jaxbHelper.load(new StreamSource(new FileInputStream("src/main/resources/PurchaseOrder.xml")));
    System.out.println(xOBJECT.getShipTo().getName());

все прошло отлично. Теперь мне просто нужно подключить его с помощью spring boot.

3 ответов


OXM определенно право для вас!

простая конфигурация java Jaxb2Marshaller будет выглядеть так:

//...
import java.util.HashMap;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
//...

@Configuration
public MyConfigClass {
    @Bean
    public Jaxb2Marshaller jaxb2Marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setClassesToBeBound(new Class[]{
           //all the classes the context needs to know about
           org.kaushik.xsds.All.class,
           org.kaushik.xsds.Of.class,
           org.kaushik.xsds.Your.class,
           org.kaushik.xsds.Classes.class
        }); //"alternatively" setContextPath(<jaxb.context>), 

        marshaller.setMarshallerProperties(new HashMap<String, Object>() {{
          put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true);
        }});

        return marshaller;
    }
}

в вашем классе приложений / услуг вы можете подойти так:

import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;  

@Component
public MyMarshallerWrapper {
   // you would rather:
   @Autowired
   private Jaxb2Marshaller  marshaller;
   // than:
   // JAXBContext jc = JAXBContext.newInstance(User.class);
   // Marshaller marshaller = jc.createMarshaller();

   // marshalls one object (of your bound classes) into a String.
   public <T> String marshallXml(final T obj) throws JAXBException {
      StringWriter sw = new StringWriter();
      Result result = new StreamResult(sw);
      marshaller.marshal(obj, result);
      return sw.toString();
   }

   // (tries to) unmarshall(s) an InputStream to the desired object.
   @SuppressWarnings("unchecked")
   public <T> T unmarshallXml(final InputStream xml) throws JAXBException {
      return (T) marshaller.unmarshal(new StreamSource(xml));
   }
}

посмотреть Jaxb2Marshaller-javadoc, и ответ


если вы просто хотите serializing/deserializing bean с XML. Я думаю jackson fasterxml - один хороший выбор:

ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(new Simple());  // serializing

Simple value = xmlMapper.readValue("<Simple><x>1</x><y>2</y></Simple>",
     Simple.class); // deserializing

maven:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

см.:https://github.com/FasterXML/jackson-dataformat-xml


Spring BOOT очень умный, и он может понять, что вам нужно с небольшой помощью.

чтобы сделать работу XML-маршалинга / unmarshalling, вам просто нужно добавить аннотации @XmlRootElement в класс и @XmlElement в поля без геттера, а целевой класс будет сериализован / десериализован автоматически.

вот пример DTO

package com.exmaple;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.Date;
import java.util.Random;

@AllArgsConstructor
@NoArgsConstructor
@ToString
@Setter
@XmlRootElement
public class Contact implements Serializable {
    @XmlElement
    private Long id;

    @XmlElement
    private int version;

    @Getter private String firstName;

    @XmlElement
    private String lastName;

    @XmlElement
    private Date birthDate;

    public static Contact randomContact() {
        Random random = new Random();
        return new Contact(random.nextLong(), random.nextInt(), "name-" + random.nextLong(), "surname-" + random.nextLong(), new Date());
    }
}

и контроллером:

пакета com.exmaple;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="/contact")
public class ContactController {
    final Logger logger = LoggerFactory.getLogger(ContactController.class);

    @RequestMapping("/random")
    @ResponseBody
    public Contact randomContact() {
        return Contact.randomContact();
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Contact editContact(@RequestBody Contact contact) {
        logger.info("Received contact: {}", contact);
        contact.setFirstName(contact.getFirstName() + "-EDITED");
        return contact;
    }
}

Вы можете проверить полный код пример: https://github.com/sergpank/spring-boot-xml

любые вопросы приветствуются.