[英]Get all tags with a specific name independent of element-level
我正在用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>
-element可以存在於文檔的各個級別,甚至可以說是標題。 然后如何從XSL中選擇它? 我猜想這與“匹配”屬性有關。 我嘗試過match =“ * / keyword”卻沒有任何運氣。
當<keyword>
-element是根的頂級子級時,此代碼有效,但在<text>
-element等內部將不起作用。
我已將您的輸入示例修改為:
<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
是在其中查找包含“ / keyword”的字符串,而不是實際的節點。
如果你試試
<xsl:template match="*[starts-with(name(), 'keyword')]">
您應該身體狀況良好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.