2017-02-16 119 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