XSLT / XML: convert apostrophe to a specific entity string
I'd like to be able to convert an apostrophe to the string '
using XSLT. I've got the following XML
<OrgName>King's College</OrgName>
I'd like to be able to output the following:
<OrgName>King's College</OrgName>
I've tried a character map but I don't think this works as you can only replace a single character with a string.
I've also tried a replace function but I'm not sure what I can do to make sure that the full string actually appears in the output file?
<xsl:value-of select='replace(Org开发者_如何学编程Name,"&apos;","&apos;")' />
In my final solution I need to be able to replace all apostrophe's in the text rather than just for one node.
Using a character map is as simple as this:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes" use-character-maps="mApos"/>
<xsl:character-map name="mApos">
<xsl:output-character character="'" string="&apos;"/>
</xsl:character-map>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<OrgName>King's College</OrgName>
the wanted, correct result is produced:
<OrgName>King's College</OrgName>
This is only a partial answer:
For replacing the character '
you may use the following:
<xsl:value-of select="replace(xs:string(str),
codepoints-to-string(39),
'&apos;')"/>
which requires XSLT/XPath 2.0. Explanation codepoints-to-string
returns a string from a sequence of code points, and 39
corresponds to the character '
'
For doing this replacement on every node of your XML ... I have no solution at the moment: will think about it.
Anyway, I hope this helps.
精彩评论