2011-12-19 65 views
2

示例XML文件如下所示提取XML標籤名稱爲XML屬性值

<a> 
<apple color="red"/> 
</a> 

我應該在XSLT寫,這樣我可以得到樣本輸出下面

<AAA> 
<BB bbb="#apple"/> <!-- if possible make it auto close --> 
</AAA> 
+0

我不知道如何將其解壓,還想着到硬編碼 如: ' **硬編碼這裏** ' – OWLDummy 2011-12-19 17:08:19

+0

您可能想看看更通用的,完全參數化的解決方案。 :) – 2011-12-19 17:53:50

回答

1

使用name()local-name()功能:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="/a"> 
    <AAA> 
     <xsl:apply-templates/> 
    </AAA> 
    </xsl:template> 

    <xsl:template match="*"> 
    <BB bbb="{concat('#', name())}"/> 
    </xsl:template> 

</xsl:stylesheet> 
+0

感謝它完美的作品〜只是因爲 '{name()}'功能〜非常感謝 – OWLDummy 2011-12-19 17:18:41

+0

@OWLDummy,不客氣。 – 2011-12-19 17:31:39

+0

@KirillPolishchuk:你的轉換的結果與OP的想要的結果*不同。請檢查並糾正。另外,我相信我的通用解決方案可能會讓人感興趣,因爲它是完全參數化的,與此答案中的硬編碼值相比。 – 2011-12-19 17:52:41

2

這裏是一個通用的解決方案,即接受該名稱替換能夠製成參數

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:param name="pReps"> 
    <e oldName="a" newName="AAA"/> 
    <e oldName="apple" newName="BB"/> 
    <a oldName="color" newName="bbb"/> 
</xsl:param> 

<xsl:variable name="vReps" select= 
    "document('')/*/xsl:param[@name='pReps']"/> 

<xsl:template match="*"> 
    <xsl:element name= 
    "{$vReps/e[@oldName = name(current())]/@newName}"> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="@*"> 
    <xsl:attribute name= 
    "{$vReps/a[@oldName = name(current())]/@newName}"> 
    <xsl:value-of select="concat('#', name(..))"/> 
    </xsl:attribute> 
</xsl:template> 
</xsl:stylesheet> 

當這種轉變應用於提供的XML文檔

<a> 
    <apple color="red"/> 
</a> 

想要的,正確的結果產生

<AAA> 
    <BB bbb="#apple"/> 
</AAA>