Pregunta

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

¿Fue útil?

Solución

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;")'/>

Otros consejos

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

<xsl:value-of select="MyElement" disable-output-escaping="yes"/>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top