How combine two element in one element?

2019-08-14 09:34发布

问题:

I want merge elements that are same for example:

<Root>
    <row>
        <WID>10</WID>
        <word>Bob</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
    <row>
        <WID>5941</WID>
        <word>Jany</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
</Root>

And result be:

<span>Bob Jany</span>

I write this but it is wrong:

<xsl:choose> 
<xsl:when test = "Ah[text()]=Ah[text()]"> 
         <span>
             <xsl:value-of select="./word"/>
         </span>
</xsl:when> 
</xsl:choose>

回答1:

An XSLT 1.0 solution using the Muenchian Grouping Method:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kRowByAh" match="row" use="Ah" />
 <xsl:template match="row[generate-id()=generate-id(key('kRowByAh', Ah)[1])]">
  <span>
    <xsl:value-of select="word"/>
    <xsl:for-each select="key('kRowByAh', Ah)[position() > 1]">
     <xsl:value-of select="concat(' ', word)"/>
    </xsl:for-each>
  </span>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<Root>
    <row>
        <WID>10</WID>
        <word>Bob</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
    <row>
        <WID>5941</WID>
        <word>Jany</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
</Root>

the wanted, correct result is produced:

<span>Bob Jany</span>


回答2:

Use grouping, with XSLT 2.0 (run by Saxon 9 or AltovaXML or XmlPrime) it is as easy as

<xsl:stylesheet version="2.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>

<xsl:template match="Root">
  <xsl:copy>
    <xsl:for-each-group select="row" group-by="Ah">
      <span><xsl:value-of select="current-group()/word"/></span>
    </xsl:for-each-group>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

When I apply the stylesheet above with Saxon 9.5 HE on the input sample

<Root>
    <row>
        <WID>10</WID>
        <word>Bob</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
    <row>
        <WID>5941</WID>
        <word>Jany</word>
        <SID>2</SID>
        <Ah>1</Ah>
    </row>
</Root>

I get the result

<Root>
   <span>Bob Jany</span>
</Root>


标签: xml xslt merge