使用XSLT编辑特定属性中的值

3

我想写我的第一个XSLT。它需要查找所有属性ref以 "$.root" 开头的所有 bind 元素,然后插入 ".newRoot"。我已经成功匹配了特定的属性,但我不知道如何将其打印为更新后的属性值。

输入示例XML:

<?xml version="1.0" encoding="utf-8" ?>
<top>
    <products>
        <product>
            <bind ref="$.root.other0"/>
        </product>
        <product>
            <bind ref="$.other1"/>
        </product>
        <product>
            <bind ref="$.other2"/>
        </product>
        <product>
            <bind ref="$.root.other3"/>
        </product>
    </products>
</top>

到目前为止,我的XSL如下:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="bind[starts-with(@ref,'$.root')]/@ref">
        <xsl:attribute name="ref">$.newRoot<xsl:value-of select="bind/@ref" /></xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

我希望从输入中产生的XML:

<?xml version="1.0" encoding="utf-8" ?>
<top>
    <products>
        <product>
            <bind ref="$.newRoot.root.other0"/>
        </product>
        <product>
            <bind ref="$.other1"/>
        </product>
        <product>
            <bind ref="$.other2"/>
        </product>
        <product>
            <bind ref="$.newRoot.root.other3"/>
        </product>
    </products>
</top>
1个回答

6

改为:

<xsl:template match="bind[starts-with(@ref,'$.root')]/@ref">
    <xsl:attribute name="ref">$.newRoot<xsl:value-of select="bind/@ref" /></xsl:attribute>
</xsl:template>

尝试:

<xsl:template match="bind[starts-with(@ref,'$.root')]/@ref">
    <xsl:attribute name="ref">$.newRoot.root<xsl:value-of select="substring-after(., '$.root')" /></xsl:attribute>
</xsl:template>

或者(更方便的语法):
<xsl:template match="bind/@ref[starts-with(., '$.root')]">
    <xsl:attribute name="ref">
        <xsl:text>$.newRoot.root</xsl:text>
        <xsl:value-of select="substring-after(., '$.root')" />
    </xsl:attribute>
</xsl:template>

注意使用.表示当前节点。在你的版本中,<xsl:value-of select="bind/@ref" />指令选择了空内容,因为ref属性已经是当前节点,并且它没有子节点。

谢谢!如果ref属性是当前节点,为什么我还要在xsl:attribute元素中命名它? - Björn
1
@Björn 如果您愿意,可以计算当前节点的名称而不是直接指定它:<xsl:attribute name="{name()}"> - michael.hor257k

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接