2

I've XML file which contains only one element

<Message>
    <Location URI ="XXX:XXX:XXX" />
</Message>

I want to read and print same XML using Java, but after print it loses white space before />

<Message>
    <Location URI ="XXX:XXX:XXX"/>
</Message>

I have tried different configuration of DocumentBuilderFactory and Transformer but the result is same.

Any Idea?

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document requestDocument = builder.parse(this.getClass().getResourceAsStream("/message-template.xml"));

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
DOMSource domSource = new DOMSource(requestDocument);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(domSource, result);

System.out.println(writer.toString());
4
  • What is the way you read and print the file? Commented Jul 29, 2018 at 17:27
  • 3
    Why is the space relevant for you? Both XML code describe the same document. Commented Jul 29, 2018 at 17:33
  • @Nikolas I've edited my question. Now you can see code snippet Commented Jul 29, 2018 at 17:41
  • "Any Idea?" Several. Stop caring if the space is there. Don't read and print, just print. Write your own set of XML tools that don't care about the XML standards and act as if the space you're concerned about matters. Commented Jul 29, 2018 at 17:48

1 Answer 1

1

Here :

DOMSource domSource = new DOMSource(requestDocument);
...
transformer.transform(domSource, result);

You transform a DOMSource into a StreamResult . A DOMSource is not not a textual representation of the XML file but a Document Object Model (DOM) tree.
So whitespaces that are not considered as relevant to represent the content of the tree are not kept in the DOMSource :

URI ="XXX:XXX:XXX" />
                  |-------> not preserved

Most of APIs to represent and manipulate XML work in this way.
If you need to keep not significant whitespace in your result, you should probably do yourself the parsing of the XML file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.