sandeep kairamkonda
sandeep kairamkonda

Reputation: 85

XSLT, How to get elements from a reoccurring node based on its position and populate the schema

Input XML:

<lines>
  <line>
     <accountings>
      <accounting>
        <account>
          <seg1>value1</seg2>
        </account>
      </accounting>
      <accounting>
        <account>
          <seg1>value2</seg2>
        </account>
      </accounting>
    </accountings>
  </line>
  <line>
    <accountings>
     <accounting>
        <account>
          <seg1>value3</seg2>
        </account>
     </accounting>
    </accountings>
  </line>
  <line>
     <account>
        <seg1>value4</seg1>
     </account>
  </line>
</lines>

OutPut XML: I have to Iterate the elements find the occurrence of segments and based on the number of accounts existed. create same number of elements with values respective

<item>
  <id>1</id>
  <vname>value1</vname>
</item>
<item>
  <id>2</id>
  <vname>value2</vname>
</item>
<item>
  <id>3</id>
  <vname>value3</vname>
</item>
<item>
  <id>4</id>
  <vname>value4</vname>
</item>

What is best way to get this solution.

below is my incomplete XSLT. I am trying to store the account data from each iteration. I wasn't looping in this code because i am already confused. Please help and complete my XSLT.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
<xsl:output method="xml" omit-xml-declaration="yes" media-type="string"/>
<xsl:template match="/">
 <xsl:variable name="SegmentData" as="element()*">
   <xsl:call-template name="CheckSegment">
     <xsl:with-param name = "vaccount" select="./*:lines/*:line/*:accountings/*:accounting/*:account"/>
   </xsl:call-template>
 </xsl:variable>
  <xsl:element name="item">
    <xsl:element name="id">
        <xsl:value-of select="position()"/>
    </xsl:element>
    <xsl:element name="vname">
        <xsl:value-of select="$SegmentData/*:vnum"/>
    </xsl:element>
  </xsl:element>
 </xsl:template>
 <xsl:template name="CheckSegment" as="element()*">
    <xsl:param name = "vaccount"/>
   <xsl:element name="vnum">
                    <xsl:value-of select="$vaccount/*:seg1"/>
                </xsl:element>
 </xsl:template>    
</xsl:stylesheet>

Upvotes: 0

Views: 40

Answers (1)

Michael Kay
Michael Kay

Reputation: 163418

From what I can see, this is simply

<xsl:template match="/">
  <xsl:for-each select="//seg1">
    <item>
      <id><xsl:value-of select="position()"/></id>
      <vname><xsl:value-of select="."/></vname>
    </item>
  </xsl:for-each>
</xsl:template>

If I've missed something in the requirement, then you need to explain it more clearly. (What do you mean by "populating the schema", for example?)

Upvotes: 1

Related Questions