我正在使用 xslt 创建一个 html 页面,将我的 xml 格式化为 html 页面,但是我得到了重复的值,但我找不到原因,下面是我的 xsl、xml 和 html。我已经在下面直接指出了我的重复值出现的位置,感谢大家的帮助!
<fieldset>
<legend>Joys of a MAD man</legend><ol>
Joys of a MAD man *********** Why is the title repeated? ************
<li>Slow Moving<a href="./Music/Splintz - Joys of a MAD Man/Slow Moving.mp3">
[Download]
</a></li>
</ol></fieldset>
我的 XML
<albums>
<album>
<title>Joys of a MAD man</title>
<track>Slow Moving</track>
</album>
<album>
<title>Single</title>
<track>None</track>
</album>
</albums>
最后是我的 xsl
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="album">
<fieldset>
<legend><xsl:value-of select="title/text()" /></legend>
<ol>
<xsl:apply-templates />
</ol>
</fieldset>
</xsl:template>
<xsl:template match="track">
<li>
<xsl:value-of select="text()" />
<a>
<xsl:attribute name="href">
<xsl:text>./Music/Splintz - Joys of a MAD Man/</xsl:text>
<xsl:value-of select="text()"/>
<xsl:text>.mp3</xsl:text>
</xsl:attribute>
[Download]
</a>
</li>
</xsl:template>
</xsl:stylesheet>
最佳答案
有built-in default template rules将文本复制到结果文档。
<xsl:apply-templates/>
是 <xsl:apply-templates select="child::node()"/>
的缩写.
您使用了xsl:apply-templates
模板内匹配 album
。当你“站在”album
上时元素,title
是被处理的子节点之一。
内置模板匹配title
输出是text()
第二次“疯狂男人的欢乐”。
有多种方法可以防止 title
第二次输出文本。你可以:
- 添加一个匹配
title
的空模板添加到您的样式表以防止内置模板匹配:-
<xsl:template match="title"/>
-
- 排除
title
来自您的apply-templates
:-
<xsl:apply-templates select="node()[not(self::title)]"/>
-
- 仅将模板应用于
track
子元素:-
<xsl:apply-templates select="track"/>
-
关于xml - XSLT 意外的重复文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6971876/