1

我有一个输出 HTML 的转换。为了避免可能在旧浏览器中中断的自关闭标签(例如<img />,而不是<img></img>),输出方法必须是html. 然后虽然应用了 URL 编码,但它破坏了我的应用程序。参见例如:

输入

<html>
<head>
</head>
<body>
{{example}}
<a href="{{example}}" >abc</a>
<img src="http://placehold.it/20x20"></img>
</body>
</html>

转型

<?xml version="1.0" encoding="utf-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" /><!-- either -->
<xsl:output method="html" indent="yes" /><!-- or -->
<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
</xsl:template>
</xsl:transform>

在第一种情况下,输出是:

<?xml version="1.0"?>
<html>
<head>
</head>
<body>
{{example}}
<a href="{{example}}">abc</a>
<img src="http://placehold.it/20x20"/>
</body>
</html>

在第二种情况下,输出是:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
{{example}}
<a href="%7B%7Bexample%7D%7D">abc</a>
<img src="http://placehold.it/20x20">
</body>
</html>

第一种情况的好处是该@href属性不是 URL 编码的。这对我的应用程序来说是必须的。第二种变体虽然不好但更好地实现了,但它<img>是自动关闭的。这不能用于<img>标签和其他一些。

有没有办法获得method="html"没有 URL 编码的好处?如果是,如何?

4

2 回答 2

2

在 XSLT 2.0 中,您可以使用序列化选项 escape-uri-attributes="no" 抑制 URL 属性的 % 编码。XSLT 1.0 中没有等价物。

于 2013-01-06T22:54:29.677 回答
1

如果使用 PHP 的 XSLT 1.0 处理器,那么您可以尝试以下解决方案...

  1. 使用方法="html";
  2. 包括这个模板...

    <xsl:template match="@href">
      <xsl:attribute name="Muttaburrasaurus">
        <xsl:value-of select="." />
      </xsl:attribute>
    </xsl:template>
    
  3. 将结果输出加载到字符串中,并将所有出现的 替换Muttaburrasaurushref

如果您将来迁移到 Java,正如您在评论提要中指出的那样,您可能会这样做,那么请确保您的处理器是 XSLT 2.0+。然后您可以使用escape-uri-attributesM.Kay 提到的功能。

于 2013-01-07T00:20:05.893 回答