我正在使用XSLT将XML转换为HTML。如果我在<xsl:output>
中指定indent='no'
,则生成的 HTML 中的相邻标签一起运行到一行中(它们之间的布局的所有空格都被删除(,这使得它很难阅读和理解。但是,如果我指定"缩进-'是'",HTML 可以很好地缩进,但这完全破坏了包含在<pre> ... </pre>
中的文本布局。
有没有办法两全其美,在保持<pre>
块不变的同时indent='yes'
?
编辑:我试图想出一个最小的例子,但我无法重现我所看到的,所以显然还有其他事情发生。FWIW,这是我尝试过的:
<?xml version='1.0'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method="html" encoding="UTF-8" indent="yes"/>
<xsl:template match="demo">
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>This is a demo</h1>
<hr/>
<xsl:apply-templates/>
<hr/>
</body>
</html>
</xsl:template>
<xsl:template match="foo">
<h2>This is foo</h2>
</xsl:template>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我将这个样式表应用于这个输入:
<demo>
<p>Some HTML</p>
<pre>this is
preformatted text
which should not be<br/>
indented</pre>
<foo/>
<hr/>
</demo>
输出如下所示:没有缩进,但至少可读。
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
</head>
<body>
<h1>This is a demo</h1>
<hr>
<p>Some HTML</p>
<pre>this is
preformatted text
which should not be<br>
indented</pre>
<h2>This is foo</h2>
<hr>
<hr>
</body>
</html>
我正在使用的实现是Java 1.8附带的。
事实证明,原始 XML 在一行上都有pre>
块,行由<br/>
而不是换行符分隔。这意味着以下输入:
<pre> public static void main(String[] args) {<br /> <textarea cols='60' rows='10'></textarea><br /> }</pre>
产生了以下输出:
<pre> public static void main(String[] args) {<br>
<textarea cols="60" rows="10"></textarea>
<br> }</pre>
解决方案是添加以下规则,将<br/>
替换为换行符:
<xsl:template match="pre//br">
<xsl:text> </xsl:text>
</xsl:template>
很抱歉浪费了您的时间。