我有一个只能使用 XSLT 解决的问题。问题是我们不希望具有相同 Id 的重复 XML 标签,但是在有多个标签的情况下,两个标签的数量字段需要加在一起。这可以在下面的 XML 中轻松演示。
输入 XML
<root>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>1</quantity>
</Line>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>2</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>1</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>1</quantity>
</Line>
</root>
期望的输出
<root>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>3</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>2</quantity>
</Line>
</root>
XSLT
启动 XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/root">
<root>
<xsl:apply-templates select="orderLine"/>
</root>
</xsl:template>
<xsl:template match="/root/oderLine">
<xsl:if test="not(sku = preceding-sibling::orderLine/sku)"> </xsl:if>
</xsl:template>
</xsl:stylesheet>
比较 Id 和 SKU
例子
输入
<root>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>1</quantity>
</Line>
<Line>
<Id>4</Id>
<sku>111222</sku>
<quantity>2</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>1</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>1</quantity>a
</Line>
</root>
期望的输出
<root>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>1</quantity>
</Line>
<Line>
<Id>4</Id>
<sku>111222</sku>
<quantity>2</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>2</quantity>
</Line>
</root>
实际输出
<root>
<Line>
<Id>4</Id>
<sku>111111</sku>
<quantity>3</quantity>
</Line>
<Line>
<Id>3</Id>
<sku>222222</sku>
<quantity>2</quantity>
</Line>
</root>
如您所见,它仅匹配 Id 而不是 SKU。