Heloo,我正在编写 xslt 1.0,我有这些输入
<Data>
<Item>
<ID>1</ID>
<Stock_ID>S1</Stock_ID>
<Stock_amount>5</Stock_amount>
</Item>
<Item>
<ID>2</ID>
<Stock_ID>S1</Stock_ID>
<Stock_amount>2</Stock_amount>
</Item>
<Item>
<ID>1</ID>
<Stock_ID>S2</Stock_ID>
<Stock_amount>2</Stock_amount>
</Item>
</Data>
我需要按项目 ID 排序的输出,以及所有股票的数量。例如:
<Data>
<Item>
<ID>1<ID>
<Stock_ID>S1
<Amount>5</Amount>
</Stock_ID>
<Stock_ID>S2
<Amount>2</Amount>
</Stock_ID>
</Item>
<Item>
<ID>2<ID>
<Stock_ID>S1
<Amount>5</Amount>
</Stock_ID>
<Stock_ID>S2
<Amount/>
</Stock_ID>
</Item>
</Data>
你有什么想法吗?谢谢。
要对具有相似属性/值的元素进行分组,您必须使用 Muenchian 分组。这是 XSLT-1.0 缺少分组功能的一种解决方法,该功能随后在 XSLT-2.0 中引入。
应用于您的问题,XSLT 代码可能如下所示(我注释了这些行作为解释 - 希望这有帮助(:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<!-- key used for Muenchian grouping -->
<xsl:key name="ids" match="ID" use="text()" />
<!-- Match the root element and use Muenchian grouping with the first for-each loop -->
<xsl:template match="/Data">
<xsl:copy> <!-- copy Data element -->
<xsl:for-each select="Item/ID[generate-id() = generate-id(key('ids',.)[1])]"> <!-- Muenchian Grouping magic -->
<Item>
<xsl:copy-of select="." /> <!-- copy ID -->
<xsl:for-each select="key('ids',.)"> <!-- loop over similar ID elements -->
<Stock_ID><xsl:value-of select="../Stock_ID" /> <!-- copy Stock_ID elements content -->
<!-- copy Stock_amount content to new Amount element -->
<Amount><xsl:value-of select="../Stock_amount" /></Amount>
</Stock_ID>
</xsl:for-each>
</Item>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出:
<Data>
<Item>
<ID>1</ID>
<Stock_ID>
S1<Amount>5</Amount>
</Stock_ID>
<Stock_ID>
S2<Amount>2</Amount>
</Stock_ID>
</Item>
<Item>
<ID>2</ID>
<Stock_ID>
S1<Amount>2</Amount>
</Stock_ID>
</Item>
</Data>