BanzaiTokyo
BanzaiTokyo

Reputation: 1404

Transformer.transform() writes the first tag on the same line as <?xml>

When I write a Document to XML using Transformer's transform() method the resulting XML document is formatted nicely - all the elements are written on separate lines and indented. Except that the very first element is written on the same line as definition: <?xml version="1.0" encoding="UTF-8" standalone="no"?><first_element>

What I'd like to have is simply the <first_element> to be written on the next line like so: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <first_element>

Is there any way to preformat XML to accomplish this before writing it to file?

Upvotes: 3

Views: 1594

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

This effect is likely to depend on which XSLT processor you are using (since there are half a dozen processors that have implemented the JAXP API, telling us that you invoke it with Transformer.transform() doesn't give us this information).

You also need to tell us whether you are setting <xsl:output indent="yes"/> - the fact that your output is "formatted nicely ... and indented" doesn't tell us one way or the other.

The conformance rules depend on which version of XSLT you are using. Generally the serialization rules have become more prescriptive in each successive release of the spec.

If you're using indent="no", then the processor isn't allowed to insert whitespace after the XML declaration unless your transformation explicitly generates it (though I know that some processor do). That's because, if the output is used as an external entity rather than as a complete document, a newline here is actually significant content. As it happens, when you set standalone="no", the output can't be used as an external entity, but the serialization rules don't take that into account.

If you're using indent="yes", the rules allow whitespace to be added here, but they don't require it - it's at the discretion of the XSLT implementation.

Upvotes: 3

Related Questions