如何使用spring编组和解组xml?

How to use spring to marshal and unmarshal xml?

我有一个 spring 启动项目。我的项目中有几个 xsds。我使用 maven-jaxb2-plugin 生成了 类。我已经使用 this 教程获得示例 spring 引导应用程序 运行。

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 类。在 Spring 中还有什么东西可以用来简化我的任务。我查看了 Spring OXM 项目,但它在 xml 中配置了应用程序上下文。 spring boot 是否有任何我可以开箱即用的东西。任何示例都会有所帮助。

编辑

我尝试了 并且我 运行 使用 main 方法进行了简单测试

    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.

将其插入即可

OXM绝对适合你!

Jaxb2Marshaller 的简单 java 配置如下所示:

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

@Configuration
public class 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
        });
        // "alternative/additiona - ly":
          // marshaller.setContextPath(<jaxb.context-file>)
          // marshaller.setPackagesToScan({"com.foo", "com.baz", "com.bar"});

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

        return marshaller;
    }
}

在您的 Application/Service class 中,您可以这样处理:

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 class 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, and a related Answer

Spring BOOT 非常聪明,只需一点帮助,它就能理解您的需求。

要使 XML marshalling/unmarshalling 工作,您只需将注释 @XmlRootElement 添加到 class 并将 @XmlElement 添加到没有 getter 和目标 class 的字段将自动 serialized/deserialized。

这是 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());
    }
}

控制器:

package 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

欢迎提问。

如果你只想要 serializing/deserializing 个带有 XML 的 bean。我认为 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

行家:

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

参考:https://github.com/FasterXML/jackson-dataformat-xml

您可以使用 StringSource / StringResult 阅读/阅读 xml 来源与 spring

 @Autowired
    Jaxb2Marshaller jaxb2Marshaller;

    @Override
    public Service parseXmlRequest(@NonNull String xmlRequest) {
        return (Service) jaxb2Marshaller.unmarshal(new StringSource(xmlRequest));
    }

    @Override
    public String prepareXmlResponse(@NonNull Service xmlResponse) {
        StringResult stringResult = new StringResult();
        jaxb2Marshaller.marshal(xmlResponse, stringResult);
        return stringResult.toString();
    }