使用XSLT生成表

时间:2013-10-21 05:34:02

标签: xml xslt xslt-2.0

我需要生成一个像;

的表格
<entry Id="..." Value="64458d"/>
<entry Id="..." Value="67788n"/>

...可以是任何值,但必须与每个Id

不同

使用此XML,

<?xml version="1.0" encoding="UTF-8"?>
<Product>
   <Item>
      <Info Id="67788n" Name="Ram X1" Warranty="3 Years" Price="$30.00" />
   </Item>
   <Item>
      <Info Id="67788n" Name="Ram X1" Warranty="3 Years" Price="$30.00" />
   </Item>
   <Item>
      <Info Id="64458d" Name="Ram N2" Warranty="2 Years" Price="$25.00" />
   </Item>
   <Item>
      <Info Id="64458d" Name="Ram N2" Warranty="2 Years" Price="$25.00" />
   </Item>
   <Item>
      <Info Id="68490e" Name="Keyboard CX1" Warranty="1 Year" Price="$20.00" />
   </Item>
</Product>

感谢

1 个答案:

答案 0 :(得分:2)

您可以通过创建这样的XSLT来生成它;

<?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
       <xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="yes" />
       <xsl:template match="Product">
          <xsl:element name="Table">
             <xsl:for-each-group select="Item/Info" group-by="@Id">
                <xsl:variable name="counter" select="position()" />
                <xsl:element name="entry">
                   <xsl:attribute name="Id">
                      <xsl:value-of select="concat('Id#', $counter)" />
                   </xsl:attribute>
                   <xsl:attribute name="Value">
                      <xsl:value-of select="distinct-values(current-group()/@Id)" />
                   </xsl:attribute>
                </xsl:element>
             </xsl:for-each-group>
          </xsl:element>
       </xsl:template>
    </xsl:stylesheet>

您将获得的输出是

<Table>
   <entry Id="Id#1" Value="67788n"/>
   <entry Id="Id#2" Value="64458d"/>
   <entry Id="Id#3" Value="68490e"/>
</Table>

我希望这就像你要找的那样。