我是xsl转换的新手,我有一个问题.
我循环遍历这样的xml:
我循环遍历这样的xml:
<PO> <Items> <Item> <Price>2</Price> <Quantity>5</Quantity> </Item> <Item> <Price>3</Price> <Quantity>2</Quantity> </Item> </Items> <QuantityTotal></QuantityTotal> </PO>
现在我想在QuantityTotal节点中插入一个值:
该值是所有项目的价格*数量的总和,在这种情况下(2 * 5)(3 * 2)= 16
我怎么能这样做,我尝试了循环和变量,但变量是不可变的所以我不知道如何实现这一点.
谢谢你的帮助
解决方法
这是一个XSLT解决方案 – 不需要扩展功能:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="QuantityTotal"> <xsl:copy> <xsl:call-template name="sumProducts"> <xsl:with-param name="pNodes" select="../Items/Item"/> </xsl:call-template> </xsl:copy> </xsl:template> <xsl:template name="sumProducts"> <xsl:param name="pNodes"/> <xsl:param name="pSum" select="0"/> <xsl:param name="pEname1" select="'Price'"/> <xsl:param name="pEname2" select="'Quantity'"/> <xsl:choose> <xsl:when test="not($pNodes)"> <xsl:value-of select="$pSum"/> </xsl:when> <xsl:otherwise> <xsl:call-template name="sumProducts"> <xsl:with-param name="pNodes" select= "$pNodes[position() > 1]"/> <xsl:with-param name="pSum" select= "$pSum + $pNodes[1]/*[name()=$pEname1] * $pNodes[1]/*[name()=$pEname2] "/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
当此转换应用于提供的XML文档时:
<PO> <Items> <Item> <Price>2</Price> <Quantity>5</Quantity> </Item> <Item> <Price>3</Price> <Quantity>2</Quantity> </Item> </Items> <QuantityTotal></QuantityTotal> </PO>
产生了想要的结果:
<PO> <Items> <Item> <Price>2</Price> <Quantity>5</Quantity> </Item> <Item> <Price>3</Price> <Quantity>2</Quantity> </Item> </Items> <QuantityTotal>16</QuantityTotal> </PO>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。