I have the following minimal code:
final var xmlString = "<parent><child>data</child></parent>";
final var xmlMapper = XmlMapper.xmlBuilder()
.enable(SerializationFeature.INDENT_OUTPUT)
.build();
final var tree = xmlMapper.reader().readTree(xmlString);
final var formattedXmlString = xmlMapper.writeValueAsString(tree);
System.out.println(formattedXmlString);
My goal is to parse and beautify the XML string for the sake of logging. I have available xmlString
on the input.
The code yields the XML beautified, but it ignores the root node caused by parsing to JSON tree (that is the default behavior of ObjectMapper
that is a parent of XmlMapper
).
<code><ObjectNode><child>data</child></ObjectNode></code><code><ObjectNode> <child>data</child> </ObjectNode> </code><ObjectNode> <child>data</child> </ObjectNode>
I expect the following instead:
<code><parent><child>data</child></parent></code><code><parent> <child>data</child> </parent> </code><parent> <child>data</child> </parent>
How to change <ObjectNode>
root to the original <parent>
? I have experimented with wrapping and unwrapping, but no luck. I want to avoid manual parsing of the root element name and Regex substitution. I also don’t have any POJO object to annotate and use as the content of xmlString
can be anything XML-ish.