我有一个大的xml文件,其中包含不同的节点集,我需要根据两个节点包含的唯一元素值使用xsl进行组合。
下面是需要转换的 xml 文件的示例:
<root>
<node1>
<funds>
<fund>
<FundId>a</FundId>
<FundName>fund a</FundName>
<SomeInfo>some info</SomeInfo>
</fund>
<fund>
<FundId>b</FundId>
<FundName>fund b</FundName>
<SomeInfo>some info</SomeInfo>
</fund>
<fund>
<FundId>c</FundId>
<FundName>fund c</FundName>
<SomeInfo>some info</SomeInfo>
</fund>
</funds>
</node1>
<node2>
<funds>
<fund>
<FundId>a</FundId>
<MaxInvestmentAmount>200</MaxInvestmentAmount>
<MinInvestmentAmount>1</MinInvestmentAmount>
</fund>
<fund>
<FundId>b</FundId>
<MaxInvestmentAmount>100</MaxInvestmentAmount>
<MinInvestmentAmount>5</MinInvestmentAmount>
</fund>
<fund>
<FundId>c</FundId>
<MaxInvestmentAmount>50</MaxInvestmentAmount>
<MinInvestmentAmount>20</MinInvestmentAmount>
</fund>
</funds>
</node2>
</root>
这是所需的输出:
<node>
<funds>
<fund>
<FundId>a<FundId/>
<FundName>fund a</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>200</MaxInvestmentAmount>
<MinInvestmentAmount>1</MinInvestmentAmount>
</fund>
<fund>
<FundId>b<FundId/>
<FundName>fund b</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>100</MaxInvestmentAmount>
<MinInvestmentAmount>5</MinInvestmentAmount>
</fund>
<fund>
<FundId>c<FundId/>
<FundName>fund c</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>50</MaxInvestmentAmount>
<MinInvestmentAmount>20</MinInvestmentAmount>
</fund>
</funds>
</node>
我尝试过模板匹配,但这似乎不像我尝试的那样有效,因为两个节点具有相同的内部节点名称,因此它们不断相互覆盖。
实现此目的的一个可靠方法是对<fund>
元素使用xsl:key
,并将FundId
作为键。此方法的一个相关限制是仅合并第一个子元素(此处<node1>
(的FundId
键。如果其他子元素包含更多值,则此方法将无法按预期工作。
下面是 XSLT-1.0 样式表:
<?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" indent="yes" />
<xsl:key name="keyFund" match="fund" use="FundId" />
<xsl:template match="/root">
<node>
<funds>
<xsl:for-each select="*[1]/funds/fund">
<fund>
<xsl:copy-of select="FundId" />
<xsl:for-each select="key('keyFund',FundId)">
<xsl:copy-of select="current()/*[not(self::FundId)]" />
</xsl:for-each>
</fund>
</xsl:for-each>
</funds>
</node>
</xsl:template>
</xsl:stylesheet>
其输出为:
<?xml version="1.0"?>
<node>
<funds>
<fund>
<FundId>a</FundId>
<FundName>fund a</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>200</MaxInvestmentAmount>
<MinInvestmentAmount>1</MinInvestmentAmount>
</fund>
<fund>
<FundId>b</FundId>
<FundName>fund b</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>100</MaxInvestmentAmount>
<MinInvestmentAmount>5</MinInvestmentAmount>
</fund>
<fund>
<FundId>c</FundId>
<FundName>fund c</FundName>
<SomeInfo>some info</SomeInfo>
<MaxInvestmentAmount>50</MaxInvestmentAmount>
<MinInvestmentAmount>20</MinInvestmentAmount>
</fund>
</funds>
</node>