假设我有一个如下所示的 XML 节点:
<item id="20">
<name>Baz</name>
<description>
If you liked this, you should check out <related id="5">Foo</related>
and <related id="7">Bar</related>!
</description>
<item>
通过 XSLT 输出描述时,我想要 text()
被渲染使得每个 <related>
节点成为 anchor 标记。我该如何去做呢?
编辑:根据基里尔的请求添加了所需的输出。我希望它看起来像这样:
If you liked this, you should check out <a href="/items/5">Foo<a> and <a href="/items/7">Bar<a>!
最佳答案
创建一个模板来覆盖相关
元素的默认处理:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="related">
<a href="/items/{@id}"><xsl:value-of select="."/></a>
</xsl:template>
</xsl:stylesheet>
输出:
<item id="20">
<name>Baz</name>
<description>
If you liked this, you should check out <a href="/items/5">Foo</a>
and <a href="/items/7">Bar</a>!
</description>
</item>
这是基本的 XSLT 模式。第一个模板实现了身份转换,它复制大多数节点不变。对于相关
元素,第二个模板会覆盖第一个模板,将它们转换为 HTML anchor 。
关于xml - 转换文本中的 XML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978091/