我正在用PHP(simpleXML)、XML文档和XSL创建html。
有没有一种方法可以将所有具有特定名称(即)的元素替换为html标记(即)。我想答案是肯定的,但是我该怎么做呢?
在我的代码中,关键字元素必须是根元素的顶部子元素才能工作。
以下不起作用:
XML:
<document>
<chapter>This is the first chapter</chapter>
<text>This is a text, with a <keyword>keyword</keyword></text>
</document>
XSL:
<xsl:template match="text">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="*[starts-with(name(), 'keyword')]">
<xsl:copy>
<b>
<xsl:value-of select="."/>
</b>
</xsl:copy>
</xsl:template>
<keyword>
-元素可以存在于文档中的所有级别,甚至可以说存在于标题中。然后我如何从XSL中选择它?我想这与match属性有关。我尝试了match="*/keyword",但没有任何运气。
当<keyword>
-元素是根的顶级子元素时,此代码可以工作,但不能在<text>
-元素内部工作。
我已将您的输入示例修改为:
<document>
<title>This is the <keyword>first</keyword> title</title>
<chapter>This is the <keyword>second</keyword> chapter</chapter>
<text>This is a text, with a <keyword>third</keyword> keyword in it.</text>
</document>
使用以下样式表:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<!-- Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- exception -->
<xsl:template match="keyword">
<b><xsl:apply-templates/></b>
</xsl:template>
</xsl:stylesheet>
您将得到以下输出:
<?xml version="1.0" encoding="utf-8"?>
<document>
<title>This is the <b>first</b> title</title>
<chapter>This is the <b>second</b> chapter</chapter>
<text>This is a text, with a <b>third</b> keyword in it.</text>
</document>
我不完全确定你想做什么,但下面的查询:
<xsl:value-of select="//keyword/text()"/>
将选择所有<keyword>
元素的内容,而不管它们在树中的位置如何。这是因为我在前面使用//
我想你想要的是这个问题。
基本上,*/keyword
正在寻找一个包含"/关键字"的字符串,而不是实际的节点。
如果你尝试
<xsl:template match="*[starts-with(name(), 'keyword')]">
你的身体应该很好。