Reputation: 6526
I have a org.w3c.dom.Document. To generate the xml is no problem. But how can I generate json out of the document ?
this is the code to get the xml string
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(document);
trans.transform(source, result);
String xmlString = sw.toString();
Upvotes: 0
Views: 4696
Reputation: 307
XmlMapper xmlMapper = new XmlMapper();
String xml= FileUtils.readFileToString(new File("test_4.xsd.xml"),Charset.defaultCharset());
JsonNode node = xmlMapper.readTree(xml.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
Upvotes: 0
Reputation: 6526
Just to solve this question. At the end I used a different approach. I saved the data in a Tree.
Then for Rendering the JSONView I used the JacksonJsonView Mapper. And for Rendering the XML I used an XML Marshaller.
Upvotes: 0
Reputation: 74790
The data models for JSON and XML are different, therefore there is no canonical transformation from XML to JSON.
If you could present your data, maybe we can propose something.
Upvotes: 2