2017-02-16 161 views
1

我有一個XML,如下所示。值都嘲笑起來只是爲了測試目的在節點XSLT內插入新節點

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<TAG1> 

    <placeholder>ghgh</placeholder> 

    <placeholder>ghg</placeholder> 

    <placeholder>ghgh</placeholder> 

    <placeholder>ghg</placeholder> 

    <placeholder>ghgh</placeholder> 

    <placeholder>ghg</placeholder> 

    <Information> 

    <InformationBody> 

     <Test>EE</Test> 

     <TestTwo>QU1RIENUVEIxICAgICAgIBI3f1QK6wEs</TestTwo> 

     <TestThree>20150119.141224508</TestThree> 

    </InformationBody> 

    </Information> 

</TAG1> 

我需要追加InformationBody標籤後,一個新的節點多用一些額外的數據我怎麼會去這樣做?我是XSLT的新手,並且提出了上述問題,但我不確定它是否正確。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <!-- Identity template, copies everything as is --> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 

    <!-- Override for target element --> 
    <xsl:template match="TAG1"> 
    <!-- Copy the element --> 
    <xsl:copy> 
     <!-- And everything inside it --> 
     <xsl:apply-templates select="@* | *"/> 
     <!-- Add new node --> 
     <xsl:element name="newNode"/> 
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

最後的結果會是什麼樣子

<Information> 
<InformationBody> 

     <Test>EE</Test> 

     <TestTwo>QU1RIENUVEIxICAgICAgIBI3f1QK6wEs</TestTwo> 

     <TestThree>20150119.141224508</TestThree> 

    </InformationBody> 

<newTag></newTag> 
</Information> 

回答

2

您可以將InformationBody元素匹配,複製它原來的樣子,那麼它被複制之後添加的元素。如下圖所示:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <!-- Identity template, copies everything as is --> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <!-- Override for target element --> 
    <xsl:template match="InformationBody"> 
     <!-- Copy the element --> 
     <xsl:copy> 
      <!-- And everything inside it --> 
      <xsl:apply-templates select="@* | node()"/> 
     </xsl:copy> 
     <!-- Add new node --> 
     <xsl:element name="newNode"/> 
    </xsl:template> 
</xsl:stylesheet> 

你的方法將工作一樣,如果有InformationBody後沒有元素。如果有,將在TAG1的所有子女之後添加newNode