2015-07-13 246 views
0

我需要的屬性和新的節點添加到現有節點XSLT - 添加屬性和新的節點到現有節點

例如:

<doc> 
    <a></a> 
    <a></a> 
    <a></a> 
    <d></d> 
    <a></a> 
    <f></f> 
</doc> 

我需要的是立即添加attrinute到<a>節點,然後添加新節點內的節點。

所以輸出會是這樣,

<doc> 
    <a id='myId'> <new_node attr="myattr"/> </a> 
    <a id='myId'> <new_node attr="myattr"/> </a> 
    <a id='myId'> <new_node attr="myattr"/> </a> 
    <d></d> 
    <a id='myId'> <new_node attr="myattr"/> </a> 
    <f></f> 
</doc> 

我寫了下面的代碼做這個任務,

<xsl:template match="a"> 

     <xsl:apply-templates select="@*|node()"/> 
     <xsl:copy> 
      <xsl:attribute name="id"> 
       <xsl:value-of select="'myId'"/> 
      </xsl:attribute>  
     </xsl:copy>  

     <new_node> 
       <xsl:attribute name="attr"> 
        <xsl:value-of select="'myattr'"/> 
       </xsl:attribute> 
     </new_node> 
</xsl:template> 

該代碼添加新的屬性,如預期的新節點,但這個問題不僅是添加到第一個節點,並且它不會在氧氣編輯器之後編譯以下五條消息。 ' An attribute node (id) cannot be created after a child of the containing element.

我該如何解決這個問題?

回答

1

你說得對,但你需要確保在任何屬性後添加任何子節點。在任何子節點之前,必須先添加屬性。

試試這個模板

<xsl:template match="a"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*"/> 
     <xsl:attribute name="id"> 
      <xsl:value-of select="'myId'"/> 
     </xsl:attribute>  
     <xsl:apply-templates select="node()"/> 
     <new_node> 
      <xsl:attribute name="attr"> 
       <xsl:value-of select="'myattr'"/> 
      </xsl:attribute> 
     </new_node> 
    </xsl:copy>  
</xsl:template> 

其實,你可以一定程度上簡化了這一點,並直接寫出來的屬性。試試這個吧

<xsl:template match="a"> 
    <a id="myId"> 
     <xsl:apply-templates select="@*|node()"/> 
     <new_node attr="myattr" /> 
    </a>  
</xsl:template> 
+0

謝謝。這工作完美:) – sanjay