I'm recieving unformatted XML strings, which must be formatted for some tasks.
Let's say I have the following input:
<phoneDetails><name>My Phone X</name><displaySize>920x480px</displaySize></phoneDetails>
My expected output would be:
<phoneDetails>
<name>My Phone X</name>
<displaySize>920x480px</displaySize>
</phoneDetails>
I have already tried to serialize the unformatted string in an object using JacksonXml and then deserializing it back to a formatted string.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Anyway, this didn't solve my problem, since the XML element names can be different. For example the XML element name
could also have the name name-for-other-purpose
. This way it would be very painful.
Does anybody know how I could solve that problem? Maybe using REGEX or something else?
I highly appreciate any kind of help, cheers!
First try of importing the XML string as regular object.
I created this class, which holds the inline XML string.
public class InlineString {
public String content;
public InlineString (String content) {
this.content = content;
}
}
After that I tried to pretty print it.
InlineString obj = new InlineString("<phoneDetails><name>My Phone X</name><displaySize>920x480px</displaySize></phoneDetails>");
ObjectMapper objectMapper = new XmlMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String xml = objectMapper.writeValueAsString(command);
But the output is not the same as expected, probably because of the regular object.
<InlineString>
<content><phoneDetails><name>My Phone X</name><displaySize>920x480px</displaySize></phoneDetails></content>
</InlineString>
CodePudding user response:
Create a
TransformerFactory
usingTransformerFactory.newInstance()
.Create an identity transformer using
factory.newTransformer()
.Set the output properties on the transformer using
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
Create a source:
new StreamSource(new StringReader(inputXmlString))
Create a result:
new StreamResult(new StringWriter())
Do the transformation using
transformer.transform(source, result)
CodePudding user response:
The JacksonXML pretty option should give you the formatting you're looking for, but you will also need to edit the object before serializing it again.