如何使用Spring将XML进行编组和解组?

26

我有一个Spring Boot项目。我的项目中有几个XSD文件。我使用Maven-jaxb2-plugin生成了类。我使用this教程运行了一个样例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类映射。此外,有没有Spring中可以使用的东西使我的任务更容易。我查看了Spring OXM项目,但它在xml中配置了应用程序上下文。Spring Boot是否有任何可以直接使用的内容。任何示例都将有所帮助。
编辑
我尝试了xerx593的答案,并使用主方法运行了一个简单的测试。
    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插件进行插入即可。

如何配置映射器并不重要。XML只是达到目的的一种手段。只需创建一个Jaxb2Marshaller并使用它即可。 - M. Deinum
@M.Deinum 所有的例子都展示了 jaxb2Marshaller 的 xml 配置,我正在寻找一个 Java 配置的例子。 - Kaushik Chakraborty
new Jaxb2Marshaller() 有什么难的? - M. Deinum
4个回答

34

OXM 绝对是适合你的!

一个简单的 Java Jaxb2Marshaller 配置如下:

//...
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类中,您可以这样处理:
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以及相关的回答。 (文档链接)(相关回答)

1
等我回到工作时,我会尝试这个,看起来正是我需要的。但是看着Javadoc,你也可以做 marshaller.setPackagesToScan("org.kaushik.xsds")(其中包含我的xjc生成的JAXB类),对吧? - daniu

10

如果您只想使用XML序列化/反序列化bean。我认为是一个不错的选择:

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


2
"fasterxml" 有很多限制 - 在使用之前请仔细查看。 - Cherry

7

Spring BOOT非常智能,只需要一点点帮助,就可以理解您的需求。

要使XML编组/解组工作,只需要在类上添加注释@XmlRootElement,在没有getter方法的字段上添加注释@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());
    }
}

控制器:

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。欢迎提出任何问题。

4
您可以使用 StringSource / StringResult 与Spring一起读取/写入XML源代码。
 @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();
    }

这个回复需要更多的描述才能获得投票。 - CodeSlave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接