如何编写格式正确的XML
我目前正在写XML到XML文档中的Java,但它的格式不正确,其格式如下:如何编写格式正确的XML
<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
这是它好 – London 2010-07-17 21:40:21
你试过
System.out.print("YOUR SPACES");
我不会试图插入字符串转换成XML,我将实际的XML转换成XML,这是不是真的什么我问-1对不起 – London 2010-07-17 20:48:16
设置OutputKeys.INDENT为“yes”应该是所需的所有多数民众赞成。可悲的是,随着jre附带的xalan版本仅在要求格式化输出时在元素之后插入换行符。你可以尝试更新版本的xalan或使用saxon,它绝对支持格式良好的输出。
的可能重复【JAVA:如何缩进XML由变压器产生的(HTTP: //stackoverflow.com/questions/1384802/java-how-to-indent-xml-generated-by-transformer) – phihag 2010-07-17 20:45:36
可能重复的是只是它不工作,让我更新我的问题 – London 2010-07-17 20:49:17
拥有您transformer.setOutputProperty试过( “缩进”, “4”);和transformerFactory.setAttribute(“indent-number”,new Integer(2)); 我问,因为您的代码不显示。 – 2010-07-17 21:00:08