2013-08-05 70 views
1

僅當子元素不具有相同的屬性時,如何將屬性傳遞給子元素?如果子元素不具有相同的屬性,則XSL將屬性傳遞給子元素

XML:

<section> 
    <container attribute1="container1" attribute2="container2"> 
     <p attribute1="test3"/> 
     <ol attribute2="test4"/> 
    <container> 
<section/> 

輸出應該是這樣的:

<section> 
    <p attribute1="test3" attribute2="test2"/> 
    <ol attribute1="container1" attribute2="test4"/> 
</section> 

這是我的嘗試:

<xsl:template match="container"> 
    <xsl:apply-templates mode="passAttributeToChild"/> 
</xsl:template> 

<xsl:template match="*" mode="passAttributeToChildren"> 
    <xsl:element name="{name()}"> 
     <xsl:for-each select="@*"> 
      <xsl:choose> 
        <xsl:when test="name() = name(../@*)"/> 
        <xsl:otherwise> 
         <xsl:copy-of select="."/> 
        </xsl:otherwise> 
      </xsl:choose> 
     </xsl:for-each> 
     <xsl:apply-templates select="*|text()"/> 
    </xsl:element> 
</xsl:template> 

任何幫助,將不勝感激;)謝謝你提前!

回答

0

屬性聲明多次覆蓋對方,所以這很容易。

<xsl:template match="container/*"> 
    <xsl:copy> 
    <xsl:copy-of select="../@*" /> <!-- take default from parent --> 
    <xsl:copy-of select="@*" /> <!-- overwrite if applicable --> 
    <xsl:apply-templates /> 
    </xsl:copy> 
</xsl:template> 

這是假設你想所有父屬性,如您的樣品似乎表明。當然,你可以決定你想繼承哪些屬性:

<xsl:copy-of select="../@attribute1 | ../@attribute2" /> 
    <xsl:copy-of select="@attribute1 | @attribute2"> 
0

試試這個。

<!-- root and static content - container --> 
<xsl:template match="/"> 
    <section> 
     <xsl:apply-templates select='section/container/*' /> 
    </section> 
</xsl:template> 

<!-- iteration content - child nodes --> 
<xsl:template match='*'> 
    <xsl:element name='{name()}'> 
     <xsl:apply-templates select='@*|parent::*/@*' /> 
    </xsl:element> 
</xsl:template> 

<!-- iteration content - attributes --> 
<xsl:template match='@*'> 
    <xsl:attribute name='{name()}'><xsl:value-of select='.' /></xsl:attribute> 
</xsl:template> 

在輸出每個子節點時,我們會迭代地跨其屬性和父節點的屬性進行傳輸。

<xsl:apply-templates select='@*|parent::*/@*' /> 

的模板在它們出現在XML的順序施加到節點。因此,父節點(container)出現在子節點之前(當然),所以它是父屬性首先由屬性模板處理。

這很方便,因爲它意味着模板將始終顯示子節點自己的屬性的首選項(如果它們已經存在),因爲它們是最後處理的,因此優先於來自父級的具有相同名稱的任何屬性。因此,父母不能否決他們。

this XMLPlayground工作演示

+0

應該可以工作,但Tomalak的解決方案更容易適用於我的樣式表。無論如何非常感謝你。 – user2652424

相關問題