xslt Merge children of 2 parents and Store in a va

2019-08-27 19:59发布

I receive an xml input like this:

  <root>
    <Tuple1>
      <child11></child11>
      <child12></child12>
      <child13></child13>
    </Tuple1>
    <Tuple1>
      <child11></child11>
      <child12></child12>
    </Tuple1>

    <Tuple2>
      <child21></child21>
      <child22></child22>
    </Tuple2>
    <Tuple2>
      <child21></child21>
      <child22></child22>
      <child23></child23>
    </Tuple2>
  </root>

How can I merge the children of each Tuple1 with children of Tuple2 and store them in a variable that will be used in the rest of xslt document? First tuple1 will be merged with first Tuple2 and second Tuple1 will be merged with 2nd Tuple2 and so on. The merged output that should be stored in variable would look like this in memory:

<root>
    <Tuple1>
      <child11></child11>
      <child12></child12>
      <child13></child13>

      <child21></child21>
      <child22></child22>
    </Tuple1>
    <Tuple1>
      <child11></child11>
      <child12></child12>

      <child21></child21>    
      <child22></child22>
      <child23></child23>
    </Tuple1>
  </root>

Is variable the best option? If we use variable, is it created once or it is created every time called? I use xslt 3.0 so solution for any version can help. Thanks and I appreciate your help)

1条回答
爷的心禁止访问
2楼-- · 2019-08-27 20:43

Here is a minimal XSLT 3 approach:

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

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="root">
     <xsl:variable name="temp1">
         <xsl:copy>
             <xsl:apply-templates select="Tuple1"/>
         </xsl:copy>
     </xsl:variable>
     <xsl:copy-of select="$temp1"/>
  </xsl:template>

  <xsl:template match="Tuple1">
      <xsl:copy>
          <xsl:copy-of select="*, let $pos := position() return ../Tuple2[$pos]/*"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Online at https://xsltfiddle.liberty-development.net/bdxtqg, I have used XPath's let instead of XSLT's xsl:variable to store the position to access the specific Tuple2.

查看更多
登录 后发表回答