2017-05-15 61 views
0

我已通過覆蓋子節點更新了我的XML。現在我需要爲標籤添加一個新節點。在父節點中添加一個新的節點,該節點用xslt中的文本更新

我的XML是:

<GrandParent> 
<Parent> 
    <Child1>test</Child1> 
    <Child2>abc</Child2> 
    <Child3>62</Child3> 
    <Child4>5000061</Child4> 
</Parent> 
<Parent> 
     <Child1>test</Child1> 
     <Child2>abc</Child2> 
     <Child3>33</Child3> 
     <Child4>5560853</Child4> 
</Parent> 
</GrandParent> 

和更新的第一個標籤,如下:使用XSLT

<GrandParent> 
<Parent> 
    <Child1>test</Child1> 
    <Child2>abc</Child2> 
    <Child3>62</Child3> 
    <Child3 >dshgfshgfhgf</Child3> 
    <Child4>5000061</Child4> 
</Parent> 
<Parent> 
     <Child1>test</Child1> 
     <Child2>abc</Child2> 
     <Child3>33</Child3> 
     <Child3>dshgfshgfhgf</Child3 > 
     <Child4>5560853</Child4> 
</Parent> 
</GrandParent> 

<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="*"/> 

<!-- identity transform --> 
<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="Parent[Child4='5000061']/Child3[.='62']"> 
    <Child3>dshgfshgfhgf</Child3> 
</xsl:template> 

</xsl:stylesheet> 

現在我王添加新節點在父標籤中。我怎樣才能做到這一點,而不會干擾當前的代碼?

+0

首先您要更換child3節點嗎? xml有2個孩子3 – Hash

回答

0

我想在兩個父標籤中添加一個新節點。

添加模板匹配家長和添加新節點有 - 例如:

<xsl:template match="Parent"> 
    <xsl:copy> 
     <xsl:apply-templates/> 
     <new-node>123</new-node> 
    </xsl:copy> 
</xsl:template> 
+0

你可以看到我的版本在這裏工作:http://xsltransform.net/jxDigTM/4恐怕我沒有時間去調試你的。 –

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="*"/> 

<!-- identity transform --> 
<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="Parent[Child4='5000061']/Child3[.='62']"> 
    <Child3>dshgfshgfhgf</Child3> 
</xsl:template> 

<xsl:template match="Parent"> 
    <xsl:copy> 
     <xsl:apply-templates/> 
     <new-Child>123</new-Child> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

Child3節點只會更改否則將保持不變。如果您將所有Child3替換爲相同的值,那麼將會是"Parent[Child4]/Child3"