gpt4 book ai didi

java - 如何编写格式正确的xml

转载 作者:行者123 更新时间:2023-12-04 06:49:57 25 4
gpt4 key购买 nike

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

最佳答案

你有没有尝试过 :

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

关于java - 如何编写格式正确的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com