London
London

Reputation: 15284

How to write properly formatted xml

I'm currently writing xml to xml doc in java but it's not properly formatted, its formatted like this :

<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, 
an evil sorceress, and her own childhood to become queen 
of the world.</description>
</book>

Instead of like this, what can I do to align it properly as the rest of the document?

<book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
</book>

I've got a response about possible duplicate, that may be the case but in my case its not working here is my code :

private void writeFile(File file) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult resultStream = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(getDocument());
            transformer.transform(source, resultStream);

            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(resultStream.getWriter().toString().trim());
            out.close();
}

Upvotes: 2

Views: 1636

Answers (3)

ant
ant

Reputation: 22948

Have you tried :

StreamSource stylesource = new StreamSource(getClass().getResourceAsStream("proper-indenting.xsl"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

Where xsl source is :

<!DOCTYPE stylesheet [
  <!ENTITY cr "<xsl:text>
</xsl:text>">
]>


    <xsl:stylesheet
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
        xmlns:xalan="http://xml.apache.org/xslt" 
        version="1.0">

        <xsl:output method="xml" indent="yes" xalan:indent-amount="3"/> 

        <!-- copy out the xml -->
        <xsl:template match="* | @*">
            <xsl:copy><xsl:copy-of select="@*"/><xsl:apply-templates/></xsl:copy>
        </xsl:template>

    </xsl:stylesheet>

Original source here

Upvotes: 4

J&#246;rn Horstmann
J&#246;rn Horstmann

Reputation: 34044

Setting OutputKeys.INDENT to "yes" should be all thats needed. Sadly the version of xalan shipped with the jre only inserts newlines after elements when asked to format the output. You could try a newer version of xalan or use saxon which definitely supports nicely formatted output.

Upvotes: 2

jasonflaherty
jasonflaherty

Reputation: 1944

Have you tried

System.out.print("YOUR SPACES");

Upvotes: -3

Related Questions