如何在xslt中使用GrandChild的值

问题描述 投票:1回答:1

我需要使用所提供孙子的价值。我曾尝试过,但无法获取孙子的价值。

这是提供给我的xml

<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>

这是我需要的xml格式

<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>

这是我尝试获取孙子的值的代码。

<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>
xslt-1.0
1个回答
0
投票

您非常接近,但这里有几件事:

  • 嵌套产品在发票模板中应用模板,以便递归应用
  • 您不需要命令式xsl-foreach-apply-templates是更好的方法。
  • 在XML中有两个错字,其中包含结束元素/b和您的xsl引号class="entity'
  • [有一个Products元素包装了Product

这是执行此操作的一种方法:

<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

© www.soinside.com 2019 - 2024. All rights reserved.