I wish to generate a generic code for parsing spec

2019-08-27 10:59发布

I wish to generate a generic code for parsing special characters in xslt. I wish to replace all special characters found in any node of the xml document with symbols of my choice.

eg special characters= "&#174"; also" &#169"; etc

I have tried something like follows but nothing happens.

<xsl:template match="*">
    <xsl:choose>
        <xsl:when test="contains(.,'&amp;ndash;')">
            <xsl:value-of select="replace(.,'&amp;ndash;','-')" />
        </xsl:when>
    </xsl:choose>
</xsl:template>

the function of character output is:

<xsl:output-character character="&#160;" string="&amp;nbsp;" />

I wish to do the opposite i.e replace string with character(replace &amp;nbsp; with &#160; )

1条回答
唯我独甜
2楼-- · 2019-08-27 11:22

If XSLT 2.0 is at your disposal, use character maps for this. You can find the relevant piece of the specification here.

Define the usage of a character map as a top-level element of your stylesheet:

<xsl:output use-character-maps="math-ops"/>

Then, determine which characters you'd like to replace with a string of your choice during serialization. A character map consists of output-character elements where the @character attribute means the character you wish to replace and @string its replacement.

The following example ensures that mathematical operators are serialized correctly (that is, for simplicity it outputs capital letters).

<xsl:character-map name="math-ops">
    <xsl:output-character character="&#x03A3;" string="SIGMA HERE"/><!--Unicode Character 'GREEK CAPITAL LETTER SIGMA' (U+03A3)-->
    <xsl:output-character character="&#x03A0;" string="PI HERE"/><!--Unicode Character 'GREEK CAPITAL LETTER PI' (U+03A0)-->
    <xsl:output-character character="&#x2713;" string="CHECK MARK"/><!--Unicode Character 'CHECK MARK' (U+2713)-->
</xsl:character-map>

Note that this only has an effect on the actual serialization, not on output you generate with xsl:result-document.

To also apply character-maps to this output, specify the use-character-maps attribute on the relevant result-document elements:

<xsl:result-document href="helloworld.xml" use-character-maps="math-ops">
  <hello>
    <world/>
  </hello>
</xsl:result-document>
查看更多
登录 后发表回答