[英]XSLT: How to compare attributes of different nodes within a for-each loop
我在比较for-each循环中两个不同节点的两个不同属性时遇到一些问题。
鉴于此XML:
<?xml version="1.0" encoding="UTF-8"?>
<test>
<cars>
<car id="1" color="blue" misc="4"/>
<car id="2" color="red" misc="3"/>
<car id="3" color="blue" misc="2"/>
<car id="n" color="black" misc="1"/>
</cars>
<bikes>
<bike id="1"/>
<bike id="2"/>
<bike id="3"/>
<bike id="n"/>
</bikes>
</test>
XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>TEST - </h2>
<xsl:variable name="bikes" select="test/bikes/bike"/>
<xsl:variable name="cars" select="test/cars/car"/>
<xsl:for-each select="$bikes">
<xsl:variable name="bikesID" select="./@id"/>
<xsl:for-each select="$cars">
<xsl:if test="$bikesID = ./@id">
<xsl:if test="./@color = 'blue'">
<xsl:value-of select="./@misc"/>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我想比较自行车和汽车的ID,如果它们相等,则对其他汽车的属性进行简单检查。请查看下面的预期结果。
测试-4 2
任何帮助是极大的赞赏。
干杯
PS:真正的问题是由于缺乏关注而导致名称空间错误。 即使看起来不像使用XPath / XSLT 2.0那样好,代码也可以正常工作。
您不需要汽车的内部循环,只需用XPath表达式替换它即可直接选择匹配的misc
属性:
<xsl:for-each select="test/bikes/bike">
<xsl:variable name="id" select="@id"/>
<xsl:value-of select="/test/cars/car[@id = $id and @color = 'blue']/@misc"/>
</xsl:for-each>
我的代码没什么大不了,但是在XSLT 2.0中,如果您不希望太冗长一些,可以编写
<xsl:value-of select="for $bike in test/bikes/bike
return test/cars/car[@id=$bike/@id]/@color"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.