Add a new node in parent node which is updated wit

2019-08-17 07:44发布

问题:

I have updated my XML by overriding a child node. Now I need to add a new node to tags.

My XML is:

<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>

And updated of first tag as below:

<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>

by using XSLT:

<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>

And now I wang to add a new node in both the parent tags. How can I do that without disturbing the current code?

回答1:

I wang to add a new node in both the parent tags.

Add a template matching the parent and add the new node there - for example:

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


回答2:

You might want to edit the question to be clear.

Just adding a new node would be,

<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 node will change only when the condition is met or else it will remain the same. If your replacing all the Child3 with same value it would be "Parent[Child4]/Child3"



标签: xml xslt