XSLT 1.0 can’t translate apostrophe

穿精又带淫゛_ 提交于 2019-12-02 11:00:55

问题


I have got the following content in my XML:

<MyElement> Cats&amp;apos; eyes </ MyElement >

When I use the following code in my XSLT 1.0:

<xsl:value-of select="MyElement" />

The output is

Cats&apos; eyes 

But I want to get

Cats’ eyes

I tried

<xsl:value-of select='translate(MyElement, "&amp;apos; ", "&apos; ")'  />

But it didn’t work , the result was ca’ ey with some eliminated characters!!!!

Any thought?

Thanks


回答1:


Your first problem is that it appears your content has been "double escaped". The entity for an apostrophe is &apos;, not &amp;apos;.

Your attempt to replace characters with translate() did not work, because it works differently than you are expecting. It is not a find/replace method. You specify a list of characters in the second argument and then the corresponding character to translate each one into in the third parameter. If there is no corresponding character in the list of characters in the third parameter then it will be removed.

You will need to use a recursive template to perform the character replacement.

For example:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:call-template name="replace-string">
            <xsl:with-param name="text" select="MyElement"/>
            <xsl:with-param name="replace" select="'&amp;apos;'"/>
            <xsl:with-param name="with" select='"&apos;"'/>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="replace-string">
        <xsl:param name="text"/>
        <xsl:param name="replace"/>
        <xsl:param name="with"/>
        <xsl:choose>
            <xsl:when test="contains($text,$replace)">
                <xsl:value-of select="substring-before($text,$replace)"/>
                <xsl:value-of select="$with"/>
                <xsl:call-template name="replace-string">
                    <xsl:with-param name="text"
                        select="substring-after($text,$replace)"/>
                    <xsl:with-param name="replace" select="$replace"/>
                    <xsl:with-param name="with" select="$with"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$text"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

Of course, with XSLT 2.0 you could just use the replace() function:

<xsl:sequence select='replace(MyElement, "&amp;apos;", "&apos;")'/>



回答2:


It's simple, just add disable-output-escaping="yes"

<xsl:value-of select="MyElement" disable-output-escaping="yes"/>


来源:https://stackoverflow.com/questions/21272212/xslt-1-0-can-t-translate-apostrophe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!