如果您希望對所有屬性或僅僅是id屬性或者它是否只是一個元素上的屬性或所有元素,您不會說。
讓我們假設您想要爲所有元素上的id屬性執行此操作,但保留其他屬性不變。然後,你將有一個模板,任何這樣的元素與ID匹配屬性,像這樣:
<xsl:template match="*[@id]">
並在此您可以根據當前元素的名稱創建一個新的元素,像這樣:
<xsl:element name="{name()}id">
<xsl:value-of select="@id" />
</xsl:element>
試試這個XSLT一開始
<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="*[@id]">
<xsl:copy>
<xsl:apply-templates select="@*[name() != 'id']" />
<xsl:element name="{name()}id">
<xsl:value-of select="@id" />
</xsl:element>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
注意,在動態創建新ELEM使用屬性值模板(大括號)的入口名稱。另請注意,您必須在創建新的子元素之前輸出其他屬性,因爲在爲其創建子元素之後輸出元素的屬性時被認爲是錯誤的。
當然,如果您有一個特定的元素上想只有ID屬性,可以簡化第二模板來此
<xsl:template match="parent[@id]">
<parent>
<xsl:apply-templates select="@*[name() != 'id']" />
<parentid>
<xsl:value-of select="@id" />
</parentid>
<xsl:apply-templates select="node()"/>
</parent>
</xsl:template>
但是,如果你想所有屬性轉換成元素,你可以這樣做這在一個完全通用的方式,像這樣
<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="@*">
<xsl:element name="{name(..)}{name()}">
<xsl:value-of select="." />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
編輯:
如果要求實際上是將id屬性添加爲子元素的子元素,則需要稍微調整一點。首先,你需要一個模板的元素將被複制
<xsl:template match="parent/@id" />
然後,你需要一個模板來匹配父元素的子點停止父是輸出的ID屬性
<xsl:template match="parent[@id]/*[1]">
(在這種情況下,我假定這將永遠是第一個子元素。如果你想要一個特定的子元素,只要使用此名稱)
在這個模板那麼你可以創建新的元素我們來自父級的id屬性。
試試這個XSLT
<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="parent/@id" />
<xsl:template match="parent[@id]/*[1]">
<xsl:copy>
<xsl:apply-templates select="@*" />
<parentid>
<xsl:value-of select="../@id" />
</parentid>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我做了一個編輯對我的回答最後這應該有希望解釋如何應對這一要求。 –
當然可以。清楚的解釋,非常感謝! – Corrr