Avatar of Letterpart
Letterpart
Flag for United Kingdom of Great Britain and Northern Ireland asked on

adding new data to XML file, updating attribute counter, via XSLT

I want add some data to the end of an existing XML file.
In a simplified form my original XML file looks like this

<?xml version="1.0"?>
<file>
  <table>
    <comment/>
    <xref>yes</xref>
    <test key="1">
      <name>nameA</name>
      <type>type7</type>
    </test>
    <test key="2">
      <name>nameC</name>
      <type>type9</type>
    </test>
  </table>
</file>

Open in new window


I want to add a new test element group with name=nameG and type=type4
I want to add it after all the existing test elements
I don't know how many test elements there are in the original XML files although i do know that value of the key attribute will match the test element count i.e. 3rd test element would have key="3"

So, knowing that I want to add a  new test element group with name=nameG and type=type4 I would want to end up with this:

<?xml version="1.0"?>
<file>
  <table>
    <comment/>
    <xref>yes</xref>
    <test key="1">
      <name>nameA</name>
      <type>type7</type>
    </test>
    <test key="2">
      <name>nameC</name>
      <type>type9</type>
    </test>
    <test key="3">
      <name>nameG</name>
      <type>type4</type>
    </test>
  </table>
</file>

Open in new window


I need a way to add this new information in via XSLT.
Can anyone point me in the right direction of how to do this?

Thanks.
XML

Avatar of undefined
Last Comment
Gertone (Geert Bormans)

8/22/2022 - Mon
Gertone (Geert Bormans)

In you xslt stylesheet add one template that does an identity transform

<xsl:template match="node()">
   <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="node()"/>
   </xsl:copy>
</xsl:template>

Open in new window

Gertone (Geert Bormans)

If you now execute the xslt, you would get the source copied exactly as the result
Now we can add a specialisation for test ( a new template that will overrule the existing only for the test element
ASKER CERTIFIED SOLUTION
Gertone (Geert Bormans)

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Letterpart

ASKER
Excellent - thanks very much Geert for the quick response, solution, and explanation!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Gertone (Geert Bormans)

Welcome