的
>假设我有以下内容:
<document>
<foods>
<food id = "1" name="apple"></food>
</foods>
<shopping-list>
<item food-id="1" qty="10"></item>
</shopping-list>
</document>
如何使用 XSLT 创建元素列表,这些元素组合了来自项目及其引用的食物的数据。
前任:
<food-item-list>
<food-item name="apple" qty="10">
</food-item>
</food-item-list>
这在 XSLT 中可能吗?还是可以使用不同的技术? 目标是不必编写程序来执行此操作。
在 XSLT 中实现这种交叉引用的有效方法是定义一个键
<xsl:key name="foodById" match="food" use="@id" />
然后,可以使用 key
函数查找给定特定id
值的food
元素。
<xsl:template match="item">
<food-item qty="{@qty}" name="{key('foodById', @food-id)/@name}" />
</xsl:template>
或者,如果您不想对属性名称进行硬编码,而只是想要两个元素的所有属性(交叉引用本身除外),那么
<xsl:template match="item">
<food-item>
<xsl:copy-of select="@*[local-name() != 'food-id']" />
<xsl:copy-of select="key('foodById', @food-id)/@*[local-name() != 'id']" />
</food-item>
</xsl:template>
如果你的问题只是 这在 XSLT 中可能吗? 是的,假设food-id
IDREF
id
<food>
,这是非常可能和容易
试试这个大小:
<xsl:for-each select="food">
<xsl:element name="food-item">
<xsl:attribute name="name">
<xsl:value-of select="@name" />
</xsl:attribute>
<xsl:attribute name="qty">
<xsl:value-of select="//shopping-list/item[@food-id=current()/@id]/@qty"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>