Home > Software design >  How to convert a one line string into a formatted XML string?
How to convert a one line string into a formatted XML string?

Time:08-19

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>&lt;phoneDetails>&lt;name>My Phone X&lt;/name>&lt;displaySize>920x480px&lt;/displaySize>&lt;/phoneDetails></content>
</InlineString>

CodePudding user response:

  1. Create a TransformerFactory using TransformerFactory.newInstance().

  2. Create an identity transformer using factory.newTransformer().

  3. Set the output properties on the transformer using transformer.setOutputProperty(OutputKeys.INDENT, "yes")

  4. Create a source: new StreamSource(new StringReader(inputXmlString))

  5. Create a result: new StreamResult(new StringWriter())

  6. 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.

  • Related