输出在xslt的属性中转义xml

时间:2013-05-14 14:13:06

标签: xml xslt

输入xml:

<Parent>
    <Child attr="thing">stuff</Child>
</Parent>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="Child">
        <newChild chars="{..}" />
    </xsl:template>
</xsl:stylesheet>

所需的输出:

<newChild chars="&lt;Child attr=&quot;thing&quot;&gt;stuff&lt;/Child&gt;" />

请注意,'chars'属性的值只是'Child'标记的转义版本。

问题:如何将当前匹配的元素输入属性?我虽然..通常会这样做,但在谈论属性时似乎没有,我只是得到一些随机的xml实体,然后是Child标签的值,例如<newChild chars="&#xA; stuff&#xA;"/>。我期待可能需要一些逃避的东西来使它有效。

任何建议表示赞赏。

(在每个人问我为什么要做这样的事情之前,我受到我正在连接的应用程序的api的约束)

2 个答案:

答案 0 :(得分:0)

看起来你必须逐步建立起来。  请注意..指向Parent。您可能希望创建"&lt;Child attr=&quot;",附加<value-of select='@attr'/>"&gt;"<value-of select="."/>"&lt;/Child>",连接所有这些并使用{{1创建字符属性}}

类似的东西:

<xsl:attribute/>

没有检查过,但希望它有所帮助。

然而,它非常容易出错。如果我不得不这样做,我可能不会使用XSLT,而是使用“toXML()”方法并在其上运行escapeXML()的DOM。

答案 1 :(得分:0)

这是JLRishe提到的解决方案的改编。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*" mode="asEscapedString">
        <xsl:text> </xsl:text>
        <xsl:value-of select="name()"/>
        <xsl:text disable-output-escaping="yes"><![CDATA[=&quot;]]></xsl:text>
        <xsl:value-of select="."/>
        <xsl:text disable-output-escaping="yes"><![CDATA[&quot;]]></xsl:text>
    </xsl:template>

    <xsl:template match="*" mode="asEscapedString">
        <xsl:text>&lt;</xsl:text>
        <xsl:value-of select="name()"/>
        <xsl:text></xsl:text>
        <xsl:apply-templates select="@*" mode="asEscapedString"/>
        <xsl:text>&gt;</xsl:text>
        <xsl:apply-templates select="node()" mode="asEscapedString"/>
        <xsl:text>&lt;/</xsl:text>
        <xsl:value-of select="name()"/>
        <xsl:text>&gt;</xsl:text>
    </xsl:template>

    <xsl:template match="Child">
        <newChild>
            <xsl:attribute name="chars">
                <xsl:apply-templates mode="asEscapedString" select="." />
            </xsl:attribute>
        </newChild>

    </xsl:template>
    <xsl:template match="*">
        <xsl:apply-templates select="Child"/>
    </xsl:template>
</xsl:stylesheet>

这将生成以下输出:

<newChild chars="&lt;Child attr=&amp;quot;thing&amp;quot;&gt;stuff&lt;/Child&gt;"/>

注意:这远离一般解决方案。这适用于您的简单示例。