我有我的传入 xml 像
<?xml version="1.0" encoding="UTF-8"?>
<RootName>
<RandomRootNode>
<RandomNode>
<Identity>1</Identity>
<Name>abc</Name>
</RandomNode>
<RandomNode>
<Identity>2</Identity>
<Name>def</Name>
</RandomNode>
<RandomNode>
<Identity>3</Identity>
<Name>ghi</Name>
</RandomNode>
</RandomRootNode>
<SeriesRootNode>
<Series>
<Identity>2</Identity>
<Total>25</Total>
</Series>
<Series>
<Identity>3</Identity>
<Total>25</Total>
</Series>
<Series>
<Identity>2</Identity>
<Total>20</Total>
</Series>
</SeriesRootNode>
</RootName>
我的输出 xml 有一个元素<sum>
该元素将使用 xslt 按照以下规则填充
- 首先在
<RandomNode>
节点和<Series>
节点中查找<Identity>
的所有匹配值 - 如果它们存在,则对
<Total>
求和
所以按照上面的例子——
<output>
<ResultSet>
<Identity>2</Identity>
<sum>45</sum>
<Identity>3</Identity>
<sum>25</sum>
</ResultSet>
</output>
如果有人知道如何实现它,请告诉我。
看看下面的 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" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<output>
<ResultSet>
<!-- Apply template for RandomNode fulfiling condition that its Identity can be found within any Series element-->
<xsl:apply-templates select="RootName/RandomRootNode/RandomNode[Identity = /RootName/SeriesRootNode/Series/Identity]" />
</ResultSet>
</output>
</xsl:template>
<xsl:template match="RandomNode">
<Identity>
<xsl:value-of select="Identity" />
</Identity>
<Sum>
<!-- Sum values of Total elements that has Identity equal to the Identity of current RandomNode -->
<xsl:value-of select="sum(/RootName/SeriesRootNode/Series[Identity = current()/Identity]/Total)" />
</Sum>
</xsl:template>
</xsl:stylesheet>
即
<?xml version="1.0" encoding="UTF-8"?>
<output>
<ResultSet>
<Identity>2</Identity>
<Sum>45</Sum>
<Identity>3</Identity>
<Sum>25</Sum>
</ResultSet>
</output>
以下是使用键的简洁有效的方法:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:key name="kSeries" match="Series/Total" use="../Identity" />
<xsl:template match="/*">
<output>
<ResultSet>
<xsl:apply-templates
select="RandomRootNode/RandomNode/Identity[key('kSeries', .)]" />
</ResultSet>
</output>
</xsl:template>
<xsl:template match="Identity">
<Identity>
<xsl:value-of select="."/>
</Identity>
<sum>
<xsl:value-of select="sum(key('kSeries', .))" />
</sum>
</xsl:template>
</xsl:stylesheet>
在示例输入上运行时,结果为:
<output>
<ResultSet>
<Identity>2</Identity>
<sum>45</sum>
<Identity>3</Identity>
<sum>25</sum>
</ResultSet>
</output>