【问题标题】:Need help transforming xml via xlst需要帮助通过 xslt 转换 xml
【发布时间】:2014-06-25 23:02:29
【问题描述】:

您好,我需要通过 xlst 1.0 对 xml 中的元素值求和并给出一定的输出。

这是我正在处理的 xml

<store> 
<counter>
    <item>
        <id>1</id>
        <name>Desk</name>
        <price>96</price>
    </item>
    <item>
        <id>1</id>
        <name>Chair</name>
        <price>323</price>
    </item>
    <item>
        <id>1</id>
        <name>Lamp</name>
        <price>52</price>
    </item>
    <item>
        <id>2</id>
        <name>Desk</name>
        <price>200</price>
    </item>
    <item>
        <id>2</id>
        <name>Chair</name>
        <price>62</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>540</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>235</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>455</price>
    </item>
    <item>
        <id>4</id>
        <name>Desk</name>
        <price>370</price>
    </item>
</counter>
</store>

并且期望的输出是:

<Name>Desk</Name>
<Sum> "sum of the Desk prices </Sum>

<Name>Chair</Name>
<Sum> "sum of the Chair prices </Sum>

<Name>Lamp</Name>
<Sum> "sum of the Lamp prices </Sum>

无论我做了什么,要么给我 000 作为元素的总和,要么输出错误。如果有人能指出我正确的方向,我将不胜感激。提前谢谢你。

【问题讨论】:

  • 请搜索 XSLT 分组。请注意,XSLT 1.0 或 2.0 的答案是不同的。
  • 嗯,您有一个输入格式和一个所需的输出格式...我认为您遇到的问题不是您没有编写任何 XSLT。或许你可以试试?
  • 当您使用 XSLT 1.0 时,我可以为您指明一种称为“Muenchian Grouping”的技术的方向。查看jenitennison.com/xslt/grouping/muenchian.html 了解更多信息。在您的情况下,您正在按名称对项目元素进行分组,因此您的密钥将是 &lt;xsl:key name="item" match="item" use="name" /&gt;。试一试,如果您不能让它工作,请编辑您的问题以显示您的 XSLT。谢谢!

标签: xml xslt


【解决方案1】:

请找到有助于满足您要求的 XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml"/>
<xsl:key name="lang" match="item" use="name"/>
<xsl:template match="/">
  <Output>
     <xsl:for-each select="//item[count(. | key('lang', name)[1]) = 1]">
        <Name>
           <xsl:value-of select="name"/>
        </Name>
        <Sum>
           <xsl:value-of select="sum(key('lang', name)//price)"/>
        </Sum>
     </xsl:for-each>
  </Output>
</xsl:template>
</xsl:stylesheet>

上述 XSLT 的输出:

<Output>
 <Name>Desk</Name>
 <Sum>1896</Sum>
 <Name>Chair</Name>
 <Sum>385</Sum>
 <Name>Lamp</Name>
 <Sum>52</Sum>
</Output>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2021-11-06
    • 2017-11-06
    • 2012-05-16
    • 2022-08-21
    • 1970-01-01
    相关资源
    最近更新 更多