【问题标题】:XSLT: need help how to add a new attribute to an existing element that will contain incremental valuesXSLT:需要帮助如何将新属性添加到将包含增量值的现有元素
【发布时间】:2021-08-10 22:22:49
【问题描述】:

XSLT:需要帮助如何将新属性(id)添加到将包含增量值的现有元素(行)。

输入:

<?xml version="1.0" encoding="UTF-8"?>
<Personal>
    <description />
    <details />
    <information>
        <Table>
            <Location>
                <location>town</location>
                <location>city</location>
                <location>country</location>
            </Location>
            <Contact>
                <row>
                    <values>
                        <ref id="0" value="name" />
                        <ref id="1" value="address" />
                    </values>
                </row>
                <row>
                    <values>
                        <ref id="0" value="name" />
                        <ref id="1" value="" />
                        <ref id="2" value="" />
                    </values>
                </row>
            </Contact>
        </Table>
    </information>
</Personal>

期望的输出:

在行元素中有一个 id 属性,其中值将从 0 开始递增

<?xml version="1.0" encoding="UTF-8"?>
<Personal>
    <description />
    <details />
    <information>
        <Table>
            <Location>
                <location>town</location>
                <location>city</location>
                <location>country</location>
            </Location>
            <Contact>
                <row id="0">
                    <values>
                        <ref id="0" value="name" />
                        <ref id="1" value="address" />
                    </values>
                </row>
                <row id="1">
                    <values>
                        <ref id="0" value="name" />
                        <ref id="1" value="" />
                        <ref id="2" value="" />
                    </values>
                </row>
            </Contact>
        </Table>
    </information>
</Personal>

我是 XSLT 的新手,我尝试的所有方法似乎都不起作用

【问题讨论】:

  • 输入是否可以包含多个Contact 元素?如果是,row 号码是否应该重新启动?
  • 只有一个联系人元素。无论如何,这已经解决了:)
  • 不要告诉我们您尝试了所有方法但没有任何效果。告诉我们你尝试过的一件事,并告诉我们它是如何失败的。这样我们就可以看到您做错了什么,并帮助您提高学习曲线。

标签: xml xslt attributes increment


【解决方案1】:

这个转换看起来很简单,你可以使用position()...

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:mode on-no-match="shallow-copy"/>
    
    <xsl:template match="row">
        <row id="{position()-1}">
            <xsl:apply-templates select="@*|node()"/>
        </row>
    </xsl:template>
    
</xsl:stylesheet>

如果您无法使用 XSLT 3.0,只需将 xsl:mode 替换为 identity transform

工作小提琴:http://xsltfiddle.liberty-development.net/3MP42Nt

【讨论】:

  • 就像一个魅力。非常感谢:)
猜你喜欢
  • 2022-10-26
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多