使用

时间:2018-03-04 20:33:22

标签: xslt xml-parsing xslt-1.0

Heloo, 我正在写xslt 1.0,我有这些输入

<Data>
 <Item>
   <ID>1</ID>
   <Stock_ID>S1</Stock_ID>
   <Stock_amount>5</Stock_amount>
 </Item>
 <Item>
   <ID>2</ID>
   <Stock_ID>S1</Stock_ID>
   <Stock_amount>2</Stock_amount>
 </Item>
 <Item>
   <ID>1</ID>
   <Stock_ID>S2</Stock_ID>
   <Stock_amount>2</Stock_amount>
 </Item>
</Data>

我需要按项目ID排序的输出,所有股票的金额。例如:

<Data>
  <Item>
    <ID>1<ID>
    <Stock_ID>S1
      <Amount>5</Amount>
    </Stock_ID>
    <Stock_ID>S2
      <Amount>2</Amount>
    </Stock_ID>
  </Item>
  <Item>
    <ID>2<ID>
    <Stock_ID>S1
      <Amount>5</Amount>
    </Stock_ID>
    <Stock_ID>S2
      <Amount/>
    </Stock_ID>
  </Item>
</Data>
你知道吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

要对具有相似属性/值的元素进行分组,您必须使用Muenchian Grouping。这是XSLT-1.0缺少分组功能的一种解决方法,然后在XSLT-2.0中引入。

应用于您的问题,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" omit-xml-declaration="yes" indent="yes"/>

  <!-- key used for Muenchian grouping -->
  <xsl:key name="ids" match="ID" use="text()" />

  <!-- Match the root element and use Muenchian grouping with the first for-each loop -->
  <xsl:template match="/Data">
    <xsl:copy>                                                   <!-- copy Data element -->
      <xsl:for-each select="Item/ID[generate-id() = generate-id(key('ids',.)[1])]">   <!-- Muenchian Grouping magic -->
        <Item>
            <xsl:copy-of select="." />                           <!-- copy ID -->
            <xsl:for-each select="key('ids',.)">                 <!-- loop over similar ID elements -->
                <Stock_ID><xsl:value-of select="../Stock_ID" />  <!-- copy Stock_ID elements content --> 
                    <!-- copy Stock_amount content to new Amount element -->
                    <Amount><xsl:value-of select="../Stock_amount" /></Amount>        
                </Stock_ID>
            </xsl:for-each>
        </Item>
      </xsl:for-each>
    </xsl:copy>      
  </xsl:template>
</xsl:stylesheet>

<强>输出:

<Data>
    <Item>
        <ID>1</ID>
        <Stock_ID>
            S1<Amount>5</Amount>
        </Stock_ID>
        <Stock_ID>
            S2<Amount>2</Amount>
        </Stock_ID>
    </Item>
    <Item>
        <ID>2</ID>
        <Stock_ID>
            S1<Amount>2</Amount>
        </Stock_ID>
    </Item>
</Data>