我正在尝试编写我的第一个 XSLT。它需要找到属性bind 以“$.root”开头的所有ref 元素,然后插入“.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>

最佳答案

代替:

<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 属性已经是当前节点 - 它没有子节点。

关于xml - 使用 XSLT 编辑特定属性中的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43077443/

10-11 02:19
查看更多