2012-03-25 85 views
1

我有一个XML,显示有看起来像字段值与字段值:XSLT把XML转换与具有相同标签的分组值

<data> 
    <currentRow> 
     <columnValue>usa</columnValue> 
     <columnValue>ma</columnValue> 
     <columnValue>boston</columnValue> 
     <columnValue>bob</columnValue> 
    </currentRow> 
    <currentRow> 
     <columnValue>usa</columnValue> 
     <columnValue>ma</columnValue> 
     <columnValue>boston</columnValue> 
     <columnValue>george</columnValue> 
    </currentRow> 
    <currentRow> 
     <columnValue>usa</columnValue> 
     <columnValue>ny</columnValue> 
     <columnValue>nyc</columnValue> 
     <columnValue>mary</columnValue> 
    </currentRow> 
    </data> 

我要生成生产,看起来像一个Xml

<Class> 
    <Student> 
    <Country>usa</Country> 
    <State>ma</State> 
    <City>boston</City> 
     <name>bob</name> 
     <name>george</name> 
    </Student> 
    <Student> 
    <Country>usa</Country> 
    <State>ny</State> 
    <City>nyc</City> 
     <name>mary</name> 
    </Student> 
<Class> 

总之,我有两个问题:

  1. 我想遍历当前行生成一个通用的XML
  2. 我想组在他们所居住的位置,学生姓名,首先在城市上空,然后状态,然后国家

任何想法,我该怎么做呢?

+0

您的输出XML无效。 ' boston '? “ ......”的缩进是否表明它应该在''元素内?请修正输出XML以显示您真正想要完成的内容。 – 2012-03-25 23:02:43

回答

1

以下样式表使用使用第一3个columnValue元素的值的Muenchian Method到组currentRow元件。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output indent="yes"/> 

    <!--Create a key grouping on the concatenated values of 
     country, state, and city separated by '-'--> 
    <xsl:key name="students-by-country-state-city" 
      match="currentRow" 
      use="concat(columnValue[1], 
         '-', 
         columnValue[2], 
         '-', 
         columnValue[3])"/> 

    <xsl:template match="data"> 
     <Class> 
      <!--apply templates to the first item in each grouping of items --> 
      <xsl:apply-templates 
       select="currentRow[generate-id() = 
            generate-id(
            key('students-by-country-state-city', 
             concat(columnValue[1], 
             '-', 
             columnValue[2], 
             '-', 
             columnValue[3]))[1] 
            )]" 
      /> 
     </Class> 
    </xsl:template> 

    <xsl:template match="currentRow"> 
     <Student> 
      <Country> 
       <xsl:value-of select="columnValue[1]"/> 
      </Country> 
      <State> 
       <xsl:value-of select="columnValue[2]"/> 
      </State> 
      <City> 
       <xsl:value-of select="columnValue[3]"/> 
      </City> 

      <!-- find all of the names for this grouping --> 
      <xsl:for-each 
       select="key('students-by-country-state-city', 
            concat(columnValue[1], 
              '-', 
              columnValue[2], 
              '-', 
              columnValue[3]))/columnValue[4]"> 
       <name> 
        <xsl:value-of select="."/> 
       </name> 
      </xsl:for-each> 
     </Student> 
    </xsl:template> 

</xsl:stylesheet>