【问题标题】:How to write properly formatted xml如何编写格式正确的xml
【发布时间】:2011-03-17 10:27:16
【问题描述】:

我目前正在用 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();
}

【问题讨论】:

  • 可能重复是的,只是它不起作用,让我更新我的问题
  • 你试过transformer.setOutputProperty("indenting", "4");和transformerFactory.setAttribute("缩进数", new Integer(2));我问是因为您的代码没有显示。
  • 我还没有尝试过,我会在稍后回复你。tnx
  • @nhnb 第一个抛出这个异常:Attempting to access invalid Transformer property 'indenting' 第二个有编译错误

标签: java xml


【解决方案1】:

你试过了吗:

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

xsl 源在哪里:

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

【讨论】:

    【解决方案2】:

    只需将 OutputKeys.INDENT 设置为“yes”即可。遗憾的是,jre 附带的 xalan 版本仅在要求格式化输出时在元素后插入换行符。您可以尝试更新版本的 xalan 或使用绝对支持格式良好的输出的 saxon。

    【讨论】:

      【解决方案3】:

      你试过了吗

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

      【讨论】:

      • 我不是在尝试将字符串插入 XML,而是将实际的 XML 插入 XML,这并不是我要求的 -1 抱歉
      猜你喜欢
      • 2014-08-21
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多