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

如何使用spring来编组和解组xml?,第1张

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

OXM绝对适合您!

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

//...import java.util.HashMap;import org.springframework.oxm.jaxb.Jaxb2Marshaller;//...@Configurationpublic class MyConfigClass {    @Bean    public Jaxb2Marshaller jaxb2Marshaller() {        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();        marshaller.setClassesToBeBound(new Class[]{//all the classes the context needs to know aboutorg.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;@Componentpublic 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));   }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5639293.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存