我是XML的新手,我似乎无法理解这个简单的问题......我正在检索一个包含节点id,make和model的表...代码工作正常...但是在桌头和身体之间,它还检索节点“john doe”..我猜XPath表达式有问题。
XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="lab1.xsl"?>
<labs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="lab.xsd">
<lab name="FOA2A">
<responsible>
<name>John</name>
<surname>Doe</surname>
</responsible>
<computers>
<computer>
<id>C001</id>
<cpu>
<make>Intel</make>
<model>Core2duo</model>
<clockspeed>2.4</clockspeed>
</cpu>
<monitor>
<type>LCD</type>
<size>17"</size>
</monitor>
</computer>
<computer>
<id>C002</id>
<cpu>
<make>AMD</make>
<model>Quad</model>
<clockspeed>3.0</clockspeed>
</cpu>
<monitor>
<type>Plasma</type>
<size>23"</size>
</monitor>
</computer>
<computer>
<id>C003</id>
<cpu>
<make>AMD</make>
<model>DoubleQuad</model>
<clockspeed>4.0</clockspeed>
</cpu>
<monitor>
<type>LED</type>
<size>32"</size>
</monitor>
</computer>
</computers>
</lab>
</labs>
XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>TEST</head>
<body>
<table border="1">
<thead>
<tr>
<td>Computer ID</td>
<td>CPU</td>
<td>Monitor</td>
</tr>
</thead>
<tbody>
<xsl:apply-templates />
</tbody>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="labs/lab/computers">
<xsl:for-each select="computer">
<tr>
<td>
<xsl:value-of select="id/text()" />
</td>
<td>
<xsl:value-of select="cpu/make/text()" />
</td>
<td>
<xsl:value-of select="cpu/model/text()" />
</td>
</tr>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
答案 0 :(得分:1)
将第二个所有模板移到apply-templates并稍后更改:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>TEST</head>
<body>
<table border="1">
<thead>
<tr>
<td>Computer ID</td>
<td>CPU</td>
<td>Monitor</td>
</tr>
</thead>
<tbody>
<xsl:for-each select="labs/lab/computers/computer">
<tr>
<td>
<xsl:value-of select="id/text()" />
</td>
<td>
<xsl:value-of select="cpu/make/text()" />
</td>
<td>
<xsl:value-of select="cpu/model/text()" />
</td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
或另一个解决方案添加select to apply-templates:
<xsl:apply-templates select="labs/lab/computers"/>