user3262519
user3262519

Reputation: 15

3 level matching in xslt

My input xml looks like as shown below

<a>  
 <b>
  <b1>ID1</b1> 
  <b2>text1</b2>
  <b3>c10</b3>
  <b3>c20</b3>
 </b>
  <b>
  <b1>ID2</b1> 
  <b2>text2</b2>
  <b3>c10</b3>
 </b>
  <b>
  <b1>ID3</b1> 
  <b2>text3</b2>
  <b3>c20</b3>
 </b>
  <c>
   <c1>c10</c1>
   <c2>text123<c2>
   <c3>d10</c3>
  </c>
  <c>
   <c1>c20</c1>
   <c2>text123<c2>
   <c3>d20</c3>
   </c>
   <d>
    <d1>d10</d1>
    <d2>text11</d2>
    <d3>10</d3>
   </d>
   <d>
    <d1>d20</d1>
    <d2>text33</d2>
    <d3>20</d3> 
   </d>
</a>

I want to sum the <d3> values for the corresponding <d1> value that comes inside corresponding <c> which finally falls under <b>. The Output should look like

<b>
 <b1>ID1</b1>
 <b4>30</b4>
<b>
<b>
 <b1>ID2</b1>
 <b4>10</b4>
<b>
<b>
 <b1>ID3</b1>
 <b4>20</b4>
<b>

Upvotes: 0

Views: 62

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117043

The output you requested is not well-formed: it lacks a root element:

The following stylesheet:

XSLT 1.0

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="c" match="c" use="c1" />
<xsl:key name="d" match="d" use="d1" />

<xsl:template match="/">
    <a>
        <xsl:for-each select="a/b">
            <b>
                <xsl:copy-of select="b1"/>
                <b4>
                    <xsl:value-of select="sum(key('d', key('c', b3)/c3)/d3)"/>
                </b4>
            </b>
        </xsl:for-each>
    </a>
</xsl:template>

</xsl:stylesheet>

when applied to your input (after correcting the unclosed elements), will return:

<?xml version="1.0" encoding="UTF-8"?>
<a>
   <b>
      <b1>ID1</b1>
      <b4>30</b4>
   </b>
   <b>
      <b1>ID2</b1>
      <b4>10</b4>
   </b>
   <b>
      <b1>ID3</b1>
      <b4>20</b4>
   </b>
</a>

Note:

In the case of:

<b>
    <b1>ID1</b1> 
    <b2>text1</b2>
    <b3>c10</b3>
    <b3>c10</b3>
</b>

the result of the sum will be 10, not - as perhaps you'd expect - 20. With such an abstract example, without a clue regarding the meaning of the data, it's hard to tell if this is the correct approach.

Upvotes: 1

Related Questions