XSL - 如何接下来为每个循环中的另一个循环链接来自不同 xml 节点的相同值



我正在努力创建一个带有 xslt 的 excel,它将通过公共属性值链接(连接(同一级别的两个节点。

下面是输入 xml:

```
<Nodes>
<Item name="ABC" category_id="A"></Item>
<Item name="DEF" category_id="B"></Item>
<Category name="First category" cat_id="A"</Category>
<Category name="Second category" cat_id="B"</Category>
</Nodes>```

和 xsl 的一部分:

<xsl:for-each select="//tc:Nodes/tc:Item">
<xsl:variable name="item_name" select="./@Name" />
<xsl:variable name="item_category_id" select="./@category_id" />
<xsl:for-each select="//tc:Nodes:tc:Category/@cat_id = $category_id">
<xsl:variable name="category_category_id" select="./@cat_id />
</xsl:for-each>
<xsl:call-template name="generateReportData">
<xsl:with-param name="item_name" select="$item_name"/>
<xsl:with-param name="item_category_id" select="$item_category_id" />
**<xsl:with-param name="category_category_id" select="$category_category_id"/>**
</xsl:call-template>
</xsl:for-each>

问题是我无法访问变量$category_category_id,因为它说它要么未定义要么超出范围。

结果应该是一行包含以下值:ABC、A、第一类别(它将通过公共类别 ID 链接来自两个节点的值(。请帮助 - 我是 xsl 的新手 - 也许还有另一种方法可以做到这一点。

问候,卢克

通过公共属性值链接(连接(同一级别的两个节点。

最好使用密钥来完成此操作。例如:

.XML

<Nodes>
<Item name="ABC" category_id="A"/>
<Item name="DEF" category_id="B"/>
<Category name="First category" cat_id="A"/>
<Category name="Second category" cat_id="B"/>
</Nodes>

XSLT 1.0

<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="cat" match="Category" use="@cat_id" />
<xsl:template match="Nodes">
<Table>
<xsl:for-each select="Item">
<Row>
<Cell>
<xsl:value-of select="@name"/>
</Cell>
<Cell>
<xsl:value-of select="key('cat', @category_id)/@name"/>
</Cell>
</Row>
</xsl:for-each>
</Table>
</xsl:template>
</xsl:stylesheet>

结果

<?xml version="1.0" encoding="UTF-8"?>
<Table>
<Row>
<Cell>ABC</Cell>
<Cell>First category</Cell>
</Row>
<Row>
<Cell>DEF</Cell>
<Cell>Second category</Cell>
</Row>
</Table>