我有一个非常不寻常的场景。以前从没听说过也没做过这样的事。这是我的源XML。
<?xml version="1.0" encoding="UTF-8"?>
<ListItems>
<List>
<name>A</name>
</List>
<List>
<name>B</name>
</List>
<List>
<name>C</name>
</List>
<List>
<name>D</name>
</List>
</ListItems>我想要做的是反转列表的顺序,添加一个反向计数器作为索引。得到的XML应该如下所示:
<UpdateListItems>
<List>
<name>D</name>
<index>4</index>
</List>
<List>
<name>C</name>
<index>3</index>
</List>
<List>
<name>B</name>
<index>2</index>
</List>
<List>
<name>A</name>
<index>1</index>
</List>
</UpdateListItems>注意按反向顺序排列的名称,并按反向顺序添加索引。听起来有点愚蠢,但是在xml转换中可以做到这一点吗?
发布于 2013-08-21 11:30:16
是的,有可能。在将模板应用于列表元素时,使用属性为“降序”的元素。
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0" >
<xsl:output method = "xml" />
<xsl:template match = "/ListItems" >
<xsl:copy>
<xsl:apply-templates select = "List" >
<xsl:sort order="descending" select="position()" data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match = "node()|@*" >
<xsl:copy>
<xsl:apply-templates select = "node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match = "List" >
<xsl:copy>
<xsl:apply-templates select = "name"/>
<index><xsl:value-of select="1 + last() - position()"/></index>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>编辑:我忘了在排序元素中包含select=“number()”数据类型=“number”属性。
再次编辑以满足您的额外要求:替换(正如Daniel已经指出的那样)
<xsl:apply-templates select = "node()|@*"/>通过这个
<xsl:apply-templates select = "name"/>或者如果你愿意你可以用这个。注意最后一个空模板,该模板禁止除子名以外的任何列表的子元素
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0" >
<xsl:output method = "xml" />
<xsl:template match = "/ListItems" >
<xsl:copy>
<xsl:apply-templates select = "List" >
<xsl:sort order="descending" select="position()" data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match = "node()|@*" >
<xsl:copy>
<xsl:apply-templates select = "node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match = "List" >
<xsl:copy>
<xsl:apply-templates select = "node()|@*"/>
<index><xsl:value-of select="1 + last() - position()"/></index>
</xsl:copy>
</xsl:template>
<xsl:template match="List/*[not(self::name)]"/>
</xsl:stylesheet>https://stackoverflow.com/questions/18355596
复制相似问题