1

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

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

这是原始记录-

  <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>

任何帮助都会很棒!谢谢

4

1 回答 1

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>
于 2013-03-02T14:39:11.637 回答