如何编写格式正确的xml

时间:2010-07-17 20:39:18

标签: java xml

我目前正在java中将xml写入xml doc,但格式不正确,格式如下:

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

而不是像这样,我可以做些什么来正确地将其与文档的其余部分对齐?

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

我得到了关于可能重复的回复,可能是这种情况,但在我的情况下,它在这里不起作用是我的代码:

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

3 个答案:

答案 0 :(得分:4)

你试过了吗?

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

xsl source是:

<!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>

原始来源here

答案 1 :(得分:2)

将OutputKeys.INDENT设置为“yes”应该是所需的全部内容。遗憾的是,随着jre一起提供的xalan版本仅在要求格式化输出时在元素之后插入换行符。您可以尝试更新版本的xalan或使用saxon,它肯定支持格式良好的输出。

答案 2 :(得分:-3)

你试过吗

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