|
1 | 1 | package com.fasterxml.jackson.databind.ext;
|
2 | 2 |
|
3 | 3 | import java.io.IOException;
|
| 4 | +import java.io.StringWriter; |
4 | 5 |
|
5 | 6 | import org.w3c.dom.Node;
|
6 | 7 | import org.w3c.dom.bootstrap.DOMImplementationRegistry;
|
|
15 | 16 | import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
|
16 | 17 | import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
17 | 18 |
|
| 19 | +import javax.xml.transform.*; |
| 20 | +import javax.xml.transform.dom.DOMSource; |
| 21 | +import javax.xml.transform.stream.StreamResult; |
18 | 22 | @SuppressWarnings("serial")
|
19 | 23 | public class DOMSerializer extends StdSerializer<Node>
|
20 | 24 | {
|
21 |
| - protected final DOMImplementationLS _domImpl; |
| 25 | + |
| 26 | + private final TransformerFactory transformerFactory; |
22 | 27 |
|
23 | 28 | public DOMSerializer() {
|
24 | 29 | super(Node.class);
|
25 |
| - DOMImplementationRegistry registry; |
26 | 30 | try {
|
27 |
| - registry = DOMImplementationRegistry.newInstance(); |
| 31 | + transformerFactory = TransformerFactory.newInstance(); |
28 | 32 | } catch (Exception e) {
|
29 |
| - throw new IllegalStateException("Could not instantiate DOMImplementationRegistry: "+e.getMessage(), e); |
| 33 | + throw new IllegalStateException("Could not instantiate TransformerFactory: "+e.getMessage(), e); |
30 | 34 | }
|
31 |
| - _domImpl = (DOMImplementationLS)registry.getDOMImplementation("LS"); |
32 | 35 | }
|
33 | 36 |
|
34 | 37 | @Override
|
35 | 38 | public void serialize(Node value, JsonGenerator jgen, SerializerProvider provider)
|
36 | 39 | throws IOException
|
37 | 40 | {
|
38 |
| - if (_domImpl == null) throw new IllegalStateException("Could not find DOM LS"); |
39 |
| - LSSerializer writer = _domImpl.createLSSerializer(); |
40 |
| - jgen.writeString(writer.writeToString(value)); |
| 41 | + try { |
| 42 | + Transformer transformer = transformerFactory.newTransformer(); |
| 43 | + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); |
| 44 | + transformer.setOutputProperty(OutputKeys.INDENT, "no"); |
| 45 | + StreamResult result = new StreamResult(new StringWriter()); |
| 46 | + DOMSource source = new DOMSource(value); |
| 47 | + transformer.transform(source, result); |
| 48 | + jgen.writeString(result.getWriter().toString()); |
| 49 | + } catch (TransformerConfigurationException e) { |
| 50 | + throw new IllegalStateException("Could not create XML Transformer: "+e.getMessage(), e); |
| 51 | + } catch (TransformerException e) { |
| 52 | + throw new IOException("XML Transformation failed: "+e.getMessage(), e); |
| 53 | + } |
41 | 54 | }
|
42 | 55 |
|
43 | 56 | @Override
|
|
0 commit comments