Concatenate two or more attributes of the same nod

2019-08-30 04:55发布

XML to XML by XSL Transformation where I want to concatenate multiple attributes like:

Sample Case:

<Sample>
  <Date Year="2012" Month="9" Day="21"/>
  <Time Hour="6" Minute="6" Second="6"/>
</Sample>

Required Output:

<Sample>
  <Date>9/21/2012</Date>
  <Time>6:6:6</Time>
</Sample>

标签: xml xslt
1条回答
再贱就再见
2楼-- · 2019-08-30 05:57

This can be achieved by extending the standard XSLT identity transform with extra templates to match your Date and Time elements, re-formatting them as required

For example, to match a Date element, with Year, Month and Day attributes, you would do this.

If you could guarantee all Date elements had the required three attributes, you could simplify the template match to just

<xsl:template match="Date">

You would add a similarl template for the Time element.

Here is the full XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes"/>
   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="Date[@Year][@Month][@Day]">
      <Date><xsl:value-of select="concat(@Month, '/', @Day, '/', @Year)" /></Date>
   </xsl:template>

   <xsl:template match="Time[@Hour][@Minute][@Second]">
      <Time><xsl:value-of select="concat(@Hour, ':', @Minute, ':', @Second)" /></Time>
   </xsl:template>
</xsl:stylesheet>

When applied to your sample XML, the following is output:

<Sample>
   <Date>9/21/2012</Date>
   <Time>6:6:6</Time>
</Sample>
查看更多
登录 后发表回答