package at.gv.egiz.moazs.scheme; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; import static at.gv.egiz.moazs.util.JAXBClassNotFoundFix.runInTheadWithClassClassLoader; /** * @author xerx593 * Source: https://stackoverflow.com/questions/44676532/how-to-use-spring-to-marshal-and-unmarshal-xml */ public class Marshaller { private final Jaxb2Marshaller jaxbMarshaller; public Marshaller(boolean isMzs) { this.jaxbMarshaller = new Jaxb2Marshaller(); jaxbMarshaller.setClassesToBeBound( at.gv.zustellung.app2mzs.xsd.ObjectFactory.class, at.gv.zustellung.app2mzs.xsd.persondata.ObjectFactory.class, at.gv.zustellung.msg.xsd.ObjectFactory.class); var map = new HashMap(); map.put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); map.put("com.sun.xml.bind.namespacePrefixMapper", new MoaZSPrefixMapper(isMzs)); jaxbMarshaller.setMarshallerProperties(map); } public String marshallXml(final T obj) { if (obj == null) { return "null"; } StringWriter sw = new StringWriter(); Result result = new StreamResult(sw); return runInTheadWithClassClassLoader(() -> { jaxbMarshaller.marshal(obj, result); return sw.toString(); }); } public T unmarshallXml(final InputStream xml) { return runInTheadWithClassClassLoader( () -> (T) jaxbMarshaller.unmarshal(new StreamSource(xml))); } }