xslt-1.0 - 如何在 xslt 中使用 GrandChild 的值
问题描述
我需要使用提供的孙子的值。我试过但无法获取孙子的价值。
这是提供给我的 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>
解决方案
你很接近,但这里有几件事:
- 将产品应用模板嵌套在发票模板中,以便递归应用
- 您不需要命令式风格
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>
推荐阅读
- angular - Leaflet MarkerCluster removeOutsideVisibleBounds 不起作用
- c# - C# WPF - 类的数据绑定 ObservableCollection 的组合框
- python - 程序没有在python中打印结果就符合要求
- apache-spark - 从数据框中动态获取列,列名将出现在变量中
- python - 尝试学习json
- c# - 修改结构变量
- visual-foxpro - Windows 10 1803 的 VFP 网络问题
- reactjs - 如何将其孩子接受的仅限父母的道具传递给父母?
- javascript - 对于成功的同源请求,Fetch 会抛出“TypeError: Failed to fetch”
- c# - 为什么以及何时需要在异步函数中等待?