我正在为一个学校项目构建一个博客网站。博客文章的内容由许多元素组成,每个元素可以是纯文本、链接、图像或视频。所有这些元素必须按照它们在 XML 文件中存储的顺序显示,并且每个元素都将显示在新的 <p>
中。标签。
因此,我们的想法是以某种方式循环所有这些元素,并且每次迭代都应该执行 `xsl:choose
决定如何显示当前迭代的元素。
以这段代码为例:当元素是 b:blogPostContent/b:blogPostText
时,如何让它只执行 TEXT 部分类型,以及元素为 b:blogPostContent/b:blogPostLink
时的 LINK 部分?
<xsl:for-each select="b:blogPostContent/*">
<p>
<!--TEXT-->
<xsl:value-of select="."/>
<!--LINK-->
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="./@target"/>
</xsl:attribute>
<xsl:attribute name="target">
_blank
</xsl:attribute>
<xsl:value-of select="."/>
</xsl:element>
</p>
</xsl:for-each>
最佳答案
使用 choose
像这样的元素:
<xsl:choose>
<xsl:when test="name() = 'b:blogPostText'">
<xsl:value-of select="."/>
</xsl:when>
<xsl:otherwise>
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="./@target"/>
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:value-of select="."/>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
另一种可能性是在单独的模板中匹配这些元素。假设您的模板与 b:blogPostContent
匹配元素(实际上,您没有显示输入 XML 的结构):
<xsl:template match="b:blogPostContent">
<p>
<xsl:apply-templates select="b:blogPostText|b:blogPostLink"/>
</p>
</xsl:template>
<xsl:template match="b:blogPostText">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="b:blogPostLink">
<a>
<xsl:attribute name="href">
<xsl:value-of select="./@target"/>
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:value-of select="."/>
</a>
</xsl:template>
请注意<xsl:element name="a">
与 <a>
完全相同。这就是为什么我缩短了符号。 (无论如何,这是不一致的,因为你没有写 <xsl:element name="p">
)。
关于xml - XSLT for-each 循环,其中每个节点都是不同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21167815/