How to use value of GrandChild in xslt

半腔热情 提交于 2020-01-21 20:07:51

问题


I need to use the value of the grandchild provided. I tried but was unable to fetch the value of the grandchild.

This is the xml provided to me

<InvoiceDocument>
<Invoice>
<d>100</d>
<a>120</a>
<Products>
<Product>
<b>11<b>
<c>12</c>
</Product>
<Product>
<b>13</b>
<c>14</c>
</Product>
</Products>
</Invoice>
</InvoiceDocument>

This is the format of xml that i require

<MessageParts>
<LedgerJournalTable class="entity">
<e>120</e>
<LedgerJournalTrans class="entity'>
<g>11</g>
<h>12</h>
</LedgerJournalTrans>
<LedgerJournalTrans class="entity'>
<g>13</g>
<h>14</h>
</LedgerJournalTrans>
</LedgerJournalTable>
</MessageParts>

This is the code through which i tried fetching the value of grandchild.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="InvoiceDocument">
    <MessageParts>
    <LedgerJournalTable class="entity">
    <xsl:apply-templates select="Invoice"/>
    <LedgerJournalTrans class="entity'>
    <xsl:for-each select="Product">
    <xsl:apply-templates select="Product"/>
    </xsl:for-each>
    </LedgerJournalTrans>
    </LedgerJournalTable>
    </MessageParts>
  </xsl:template>

  <xsl:template match="Invoice">
  <e><xsl:value-of select="normalize-space(a/text()[1])"/></e>
  </xsl:template>


   <xsl:template match="Product">
  <g><xsl:value-of select="normalize-space(b/text()[1])"/></g>
  <h><xsl:value-of select="normalize-space(c/text()[1])"/></h>
  </xsl:template>

</xsl:stylesheet>

回答1:


You're pretty close, but there's a couple things here:

  • Nest the Product apply templates inside the Invoice template, in order to apply it recursively
  • You don't need the imperative style xsl-foreach - apply-templates is the better approach.
  • There's a couple typos in the xml with closing elements /b and in your xsl quotes class="entity'
  • There is a Products element which wraps Product

Here's one way to do this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="InvoiceDocument">
    <MessageParts>
      <LedgerJournalTable class="entity">
        <xsl:apply-templates select="Invoice"/>
      </LedgerJournalTable>
    </MessageParts>
  </xsl:template>

  <xsl:template match="Invoice">
       <e><xsl:value-of select="normalize-space(a/text()[1])"/></e>
       <xsl:apply-templates select="Products/Product"/>
  </xsl:template>

  <xsl:template match="Product">
      <LedgerJournalTrans class="entity">
         <g><xsl:value-of select="normalize-space(b/text()[1])"/></g>
         <h><xsl:value-of select="normalize-space(c/text()[1])"/></h>
      </LedgerJournalTrans>
  </xsl:template>
</xsl:stylesheet>

Working fiddle here



来源:https://stackoverflow.com/questions/59540533/how-to-use-value-of-grandchild-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!