2016-07-01 31 views
1

我有這樣的XML文檔:如何繼承當前XSLT上下文中的元素名稱?

<?xml version="1.0" encoding="utf-8" ?> 
<article properName="Article"> 
    <h1> 
    This <strong>is a header</strong> 
    </h1> 
    <p>This is a <strong>paragraph</strong</p> 
</article> 

我需要將其轉換成這樣:

<?xml version="1.0" encoding="utf-8" ?> 
<Article> 
    <Article-bigheader> 
    This <Article-bigheader-bold>is a header</Article-bigheader-bold> 
    </Article-bigheader> 
    <Article-paragraph>This is a <Article-paragraph-bold>paragraph</Article-paragraph-bold></Article-paragraph> 
</Article> 

元素在原始文檔中都會有不同的名稱和嵌套方式不同,所以我需要動態執行此操作,而不是爲每個可能的組合創建一個xsl模板。我遇到問題的具體部分是文本修飾,如何使用包含XSLT元素的名稱和附加的「-bold」後綴創建元素? 這是我到目前爲止有:

<xsl:template match="/article"> 
    <xsl:element name="{@properName}"> 
     <xsl:apply-templates/> 
    </xsl:element> 
</xsl:template> 
<xsl:template match="h1"> 
    <xsl:element name="{concat(/article/@properName, '-', 'bigheader')}"> 
     <xsl:apply-templates/> 
    </xsl:element> 
</xsl:template> 
+0

您在使用XSLT 1.0還是2.0? –

回答

0

也許你應該嘗試一下這種方法:

XSLT 1.0

<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"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="@*|node()"> 
    <xsl:param name="name"/> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"> 
      <xsl:with-param name="name" select="$name"/> 
     </xsl:apply-templates> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*[@properName]"> 
    <xsl:element name="{@properName}"> 
     <xsl:apply-templates> 
      <xsl:with-param name="name" select="@properName"/> 
     </xsl:apply-templates> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="h1"> 
    <xsl:param name="name"/> 
    <xsl:element name="{concat($name, '-', 'bigheader')}"> 
     <xsl:apply-templates> 
      <xsl:with-param name="name" select="concat($name, '-', 'bigheader')"/> 
     </xsl:apply-templates> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="p"> 
    <xsl:param name="name"/> 
    <xsl:element name="{concat($name, '-', 'paragraph')}"> 
     <xsl:apply-templates> 
      <xsl:with-param name="name" select="concat($name, '-', 'paragraph')"/> 
     </xsl:apply-templates> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="strong"> 
    <xsl:param name="name"/> 
    <xsl:element name="{concat($name, '-', 'bold')}"> 
     <xsl:apply-templates> 
      <xsl:with-param name="name" select="concat($name, '-', 'bold')"/> 
     </xsl:apply-templates> 
    </xsl:element> 
</xsl:template> 

</xsl:stylesheet> 
+0

這很好,謝謝! – FabianGillenius

相關問題