好的,我正在从这里学习一些简单的教程:
http://www.cch.kcl.ac.uk/legacy/teaching/7aavdh06/xslt/html/module_06.html
第一个练习涉及创建一个产生特定输出的转换。不幸的是,虽然我很接近,但我一开始就得到了不需要的元素。即
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xhtml"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<xsl:template match="/div/placeName">
<html>
<head />
<body>
<Table>
<tr>
<td>Place Name</td>
<td>
<xsl:value-of select="name" />
</td>
</tr>
<tr>
<td>Place Name (regularised)</td>
<td>
<xsl:value-of select="@reg" />
</td>
</tr>
<tr>
<td>National Grid Reference</td>
<td>
<xsl:value-of select="@key" />
</td>
</tr>
<tr>
<td>Type of building/monument</td>
<td>
<xsl:value-of select="settlement/@type" />
</td>
</tr>
</Table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但我得到的输出是:
Location
Place Name Old Warden
Place Name (regularised) Old Warden, St Leonard
National Grid Reference TL 137 443
Type of building/monument Parish church
其余部分都很好,但“位置”是不需要的。源 XML 位于上面的链接中。知道如何阻止不需要的文本出现吗?或者,更好的是,告诉我哪里出错了! :)
编辑:这是输出
<?xml version="1.0" encoding="utf-8" ?>
Location
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<table>
<tr>
<td>Place Name</td>
<td>Old Warden</td>
</tr>
<tr>
<td>Place Name (regularised)</td>
<td>Old Warden, St Leonard</td>
</tr>
<tr>
<td>National Grid Reference</td>
<td>TL 137 443</td>
</tr>
<tr>
<td>Type of building/monument</td>
<td>Parish church</td>
</tr>
</table>
</body>
</html>
最佳答案
正如 Stivel 提到的,“位置”文本确实来自 XML 中的 head 元素。
<div type="location">
<head n="I">Location</head>
<placeName reg="Old Warden, St Leonard" key="TL 137 443">
它出现的原因是 XSTL 的内置模板,当您未指定它在 XSLT 中查找的元素的匹配项时,它会使用该模板。
您可以在W3C page阅读内置模板。但简而言之,如果 XSLT 找不到匹配项,它将继续处理元素的子元素(不复制元素),或者在文本或属性的情况下,输出值。
XSLT 将首先查找文档元素的匹配项,如果您尚未提供模板,它将继续查找根元素的模板,然后是其子元素,依此类推。
在您的情况下,您直到 /div/placeName 才提供匹配任何内容的模板,这意味着 XSLT 将使用 div 元素的内置模板。这有两个 child ; head 和 placeName。您有一个可用于 placeName 的模板,但不能用于 head,因此内置模板最终会输出 head 的文本,因为您没有告诉它任何其他事情。
解决方案是简单地添加一个模板来忽略 head 元素
<xsl:template match="/div/head" />
这是完整的 XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xhtml"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" indent="yes" />
<xsl:template match="/div/head" />
<xsl:template match="/div/placeName">
<html>
<head />
<body>
<Table>
<tr>
<td>Place Name</td>
<td>
<xsl:value-of select="name" />
</td>
</tr>
<tr>
<td>Place Name (regularised)</td>
<td>
<xsl:value-of select="@reg" />
</td>
</tr>
<tr>
<td>National Grid Reference</td>
<td>
<xsl:value-of select="@key" />
</td>
</tr>
<tr>
<td>Type of building/monument</td>
<td>
<xsl:value-of select="settlement/@type" />
</td>
</tr>
</Table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
当您使用它时,它应该会提供您需要的输出。
关于XSLT:我的转换添加了一个未选择的元素。我缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13122632/