在xsl中测试名称空间限定属性名称的正确方法是什么:if?

时间:2015-02-27 21:54:12

标签: xml xslt xslt-2.0 saxon

我正在使用xslt 2.0来测试xsl:if内的namespace-qualitfied属性的名称。我有一个解决方案,但我相信它是一个弱的,对特定的命名空间前缀敏感。有关工作示例问题,请参阅http://xsltransform.net/jyH9rMs/1

示例输入:

<?xml version="1.0" encoding="utf-8"?>
<content xmlns:ex="http://example.com">
    <ex:t1>some content</ex:t1>
    <ex:t2>some content</ex:t2>
    <t3 ex:attr1="attr-val-1" ex:attr2="attr-val-2">more content</t3>
</content>

期望的输出:

<?xml version="1.0" encoding="UTF-8"?>
<content xmlns:ex="http://example.com">
    <ex:t1>some content</ex:t1>

    <t3 ex:attr1="attr-val-1">more content</t3>
</content>

在我的样式表中,我使用类似的逻辑来迭代元素和属性。对于元素,我可以使用self::ex:t1进行测试,但我必须求助name()='ex:attr1'来获取属性。如果样式表中的名称空间前缀从ex更改为ex1,则此属性逻辑将失败。 self::似乎不适用于属性节点,或者至少我无法使其工作。

  

xsl:if中测试命名空间限定的正确方法是什么   属性名称?

我的样式表:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:ex="http://example.com" version="2.0">
    <xsl:output method="xml" 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="ex:*">
        <xsl:for-each select=".">
            <xsl:if test="self::ex:t1">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="*[@ex:*]">
        <xsl:copy>
            <xsl:for-each select="@*">
                <xsl:if test="name()='ex:attr1'">
                <!--<xsl:if test="self::ex:attr1">-->
                    <xsl:attribute name="{name()}" select="."/>
                </xsl:if>
            </xsl:for-each>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:transform>

修改 在我的生产系统中,从中提取了上述问题,我最终使用了Michael Kay / Martin Honnen建议的方法之一:<xsl:if test=". instance of attribute(ex:attr1)">。它很干净,直接表达了意图。

其他解决方案正常运行,但我不喜欢..<xsl:if test=". is ../@ex:attr1"><xsl:if test="node-name(.)= resolve-QName('ex:attr1', ..)">的弱隐含依赖关系。 <xsl:if test="node-name(.) = QName('http://example.com', 'attr1')">必须输入命名空间URL。

2 个答案:

答案 0 :(得分:2)

选项包括

test=". instance of attribute(ex:attr1)"

test="node-name(.) = QName('namespace', 'attr1')"

test=". is ../@ex:attr1"

答案 1 :(得分:0)

一个例子不能代替解释。以下样式表可以准确地生成您要求的结果 - 无论是设计还是巧合:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ex="http://example.com">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

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

<!-- remove ex:t2 -->
<xsl:template match="ex:t2"/>

<!-- remove ex:attr2 -->
<xsl:template match="@ex:attr2"/>

</xsl:stylesheet>

请注意,此处无需测试。


是的,你对self::轴是正确的:它永远不会导致属性(或命名空间)。不,这与名称空间中的属性无关。