在xslt中的新节点下分组元素

时间:2013-03-02 13:53:44

标签: xslt grouping

我需要将一些元素组合在一起,并在一个新元素下将它们组合在一起。

下面是一个示例记录,我想将地址信息组合成一个附加层。

这是原始记录 -

  <Records>
    <People>
     <FirstName>John</FirstName>  
     <LastName>Doe</LastName>  
     <Middlename />
     <Age>20</Age>  
     <Smoker>Yes</Smoker>  
     <Address1>11 eleven st</Address1>  
     <Address2>app 11</Address2>
     <City>New York</City>
     <State>New York</State>
     <Status>A</Status>
    </People>
  </Records>

预期结果:我需要在新元素下对地址数据进行分组 -

  <Records>
    <People>
     <FirstName>John</FirstName>  
     <LastName>Doe</LastName>  
     <Middlename />
     <Age>20</Age>  
     <Smoker>Yes</Smoker>
     <Address>       
       <Address1>11 eleven st</address1>  
       <Address2>app 11</address2>
       <City>New York</City>
       <State>New York</State>
     </Address>       
     <Status>A</Status>
    </People>
  </Records>

任何帮助都会很棒!谢谢

1 个答案:

答案 0 :(得分:1)

这应该这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()" name="copy">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="People">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()[not(self::Address1 or 
                                                   self::Address2 or 
                                                   self::City or 
                                                   self::State)]" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Smoker">
    <xsl:call-template name="copy" />
    <Address>
      <xsl:apply-templates select="../Address1 | 
                                   ../Address2 | 
                                   ../City | 
                                   ../State" />
    </Address>
  </xsl:template>
</xsl:stylesheet>

在输入XML上运行时,会产生:

<Records>
  <People>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Middlename />
    <Age>20</Age>
    <Smoker>Yes</Smoker>
    <Address>
      <Address1>11 eleven st</Address1>
      <Address2>app 11</Address2>
      <City>New York</City>
      <State>New York</State>
    </Address>
    <Status>A</Status>
  </People>
</Records>
相关问题