在某些情况下,XSLT copy-of似乎在节点之间添加换行符

时间:2014-10-12 11:29:51

标签: html xslt xhtml

我正在使用xslt将xml转换为html。

传入xml的一部分包含使用 xslt:copy-of 直接复制到 pre 标记内的输出的节点。

我遇到的问题是,复制节点的一部分插入了换行符,而原始XML中没有换行符。换行符扰乱了格式,因为pre标签对html正文中的换行符很敏感。

我使用Microsoft Msxml2.FreeThreadedDOMDocument.6.0来保存XML并执行转换。我使用的是XSLT 2.0版,并且缩进="没有" xsl:output节点中的method =" xml"

添加换行符的特定情况似乎是两个html标记彼此之间具有插入空格而没有其他文本。以下是要转换的XML节点的实际文本:

<span field='text'>
  <a href="aa">aa</a><a href="bb">bb</a>
  <a href="cc">cc</a> <a href="dd">dd</a>
  <a href="ee">ee</a>- -<a href="ff">ff</a>
</span>

为了便于说明,节点内有三行。每行包含两个超链接,第一个没有插入空间,第二个带有插入空间,第三个带有插入文本,包含空格。

转换的相关部分是:

<pre style="margin-left: 2em" ><xsl:copy-of select=" span[@field='text'] "/></pre>

生成的输出HTML文本是:

<pre style="margin-left: 2em"><span field="text" xmlns=""><a href="aa">aa</a><a href="bb">bb</a>
<a href="cc">cc</a>
<a href="dd">dd</a>
<a href="ee">ee</a>- -<a href="ff">ff</a>
</span></pre>

第一行和第三行已按提供的方式输出,但第二行(锚标记具有单个居间空间)已分为两行。

我尝试在转换中使用<xsl:copy-of select="span[@field='text']/node() " />形式,但这会删除所有换行符,因此不会保留任何布局。

我做错了吗?此行为是否特定于Microsoft XML?

非常感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:2)

  

此行为是否特定于Microsoft XML?

这很容易找到:将您的结果与撒克逊6.5.5进行比较:http://xsltransform.net/bFDb2BX

请注意添加<xsl:strip-space elements="*"/>指令的效果:http://xsltransform.net/bFDb2BX/1

-
附:由于上面第一个版本的呈现的结果是:

,我不确定您在这里使用<pre>标记完成了什么。

enter image description here

答案 1 :(得分:2)

我能够在http://home.arcor.de/martin.honnen/xslt/test2014101201.html中重现问题但是当我在输入DOM文档上设置preserveWhiteSpace = true时,就像在http://home.arcor.de/martin.honnen/xslt/test2014101203.html中所做的那样,问题就消失了。 因此,显示如何使用preserveWhiteSpace解决问题的完整测试用例是

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Test</title>



<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var xmlMarkup = "<span field='text'>\n  <a href=\"aa\">aa</a><a href=\"bb\">bb</a>\n  <a href=\"cc\">cc</a> <a href=\"dd\">dd</a>\n  <a href=\"ee\">ee</a>- -<a href=\"ff\">ff</a>\n</span>";
var xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
xmlDoc.preserveWhiteSpace = true;
xmlDoc.loadXML(xmlMarkup);

var xslDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
xslDoc.loadXML([
    '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">',
    '<xsl:output method="xml" indent="no"/>',
    '<xsl:template match="/">',
    '<pre>',
    '<xsl:copy-of select="span[@field = \'text\']"/>',
    '</pre>',
    '</xsl:template>',
    '</xsl:stylesheet>'].join('\n'));

document.getElementById('output').value = xmlDoc.transformNode(xslDoc);
}//]]>  

</script>


</head>
  <body>
  <textarea id="output" rows="10" cols="80"></textarea>

</body>


</html>

然后在Windows 8.1上的IE 11中测试的输出是

<?xml version="1.0"?><pre><span field="text">
  <a href="aa">aa</a><a href="bb">bb</a>
  <a href="cc">cc</a> <a href="dd">dd</a>
  <a href="ee">ee</a>- -<a href="ff">ff</a>
</span></pre>