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

Letterpart
Letterpart used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Gertone (Geert Bormans)Information Architect
Top Expert 2006

Commented:
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)Information Architect
Top Expert 2006

Commented:
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
Information Architect
Top Expert 2006
Commented:
<xsl:template match="test">
   <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="node()"/>
   </xsl:copy>
<xsl:if test="not(following-sibling::test)">
   Add your element here
</xsl:if>
</xsl:template>

Open in new window

Author

Commented:
Excellent - thanks very much Geert for the quick response, solution, and explanation!
Gertone (Geert Bormans)Information Architect
Top Expert 2006

Commented:
Welcome

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial