Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

Escaped apostrophe in XML attributes, using XSLT

Probably being stupid, but is there a way to include an escaped apostrophe in an xml attribute using xslt?

As far as I understand, characters like the apostrophe are valid in xml elements, but not in their attributes. As a result, I'm trying to escape ' to ' in the output - but I'm running into a bit of bother.

I've tried all sorts, like using xsl:text/disable-output-escaping, ', CDATA (among others) and the closest I've been able to get is to double escape the ampersand like this: '

But I think this means I'm left with the character for an ampersand and separately, the text apos;, rather than the proper ' I'm after.


Input xml:

<?xml version="1.0" encoding="UTF-8"?>
<boof>
    <moo></moo>
</boof>

Current XSL

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="moo">
        <xsl:element name="moo">
            <xsl:attribute name="att">&amp;apos;</xsl:attribute>
        </xsl:element>
    </xsl:template>
</xsl:transform>

Current output

<boof>
    <moo att="&amp;apos;"/>
</boof>

Desired output

<boof>
    <moo att="&apos;"/>
</boof>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

is there a way to include an escaped apostrophe in an xml attribute using xslt?

No. Whether a character is escaped or not is immaterial.

<moo att="'" /> and <moo att="&apos;" /> are exactly the same thing. They describe identical nodes, once the document is parsed they will be indistinguishable.

If you have code that relies on &apos; being there, that code is broken and that's the code you need to fix.

The following will all produce the same result:

<xsl:template match="moo">
    <xsl:element name="moo">
        <xsl:attribute name="att">&apos;</xsl:attribute>
    </xsl:element>
</xsl:template>

or, for short

<xsl:template match="moo">
    <xsl:element name="moo">
        <xsl:attribute name="att">'</xsl:attribute>
    </xsl:element>
</xsl:template>

or, even shorter

<xsl:template match="moo">
    <moo att="'" />
</xsl:template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...