tags:

views:

83

answers:

3

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();
}
A: 

Have you tried

System.out.print("YOUR SPACES");
buildakicker
I'm not trying to insert string into XML, I'm inserting actual XML into XML, that is not really what I asked for -1 sorry
London
+2  A: 

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.

Jörn Horstmann
+3  A: 

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 :

http://forums.sun.com/thread.jspa?threadID=562510

c0mrade
this is it , good
London