Hi guys,
Im brand new to doing tansformations and cannot seem to wrap my head around it.
I have a Xml File which looks something like

<parentNode>
  <childnode1 att1="1" att2="2"/>
  <childnode2></childnode2>
  <childnode1 att1="1" att2="2"/>
  <childnode21></childnode21>
  <childnode1 att1="1" att2="2"/>
  <childnode22></childnode22>
  <childnode1 att1="1" att2="2"/>
  <childnode23></childnode23>
  <childnode1 att1="1" att2="2"/>
  <childnode24></childnode24>
  <optionalNode></optionalNode>
</parentNode>

The childnode labled ChildNode1 is repeated several times (the values are identical) and what i am trying to do is transform this xml into a new xml which only has one childnode1
and teh rest are "deleted" or ignored during the transformation.Everything else must stay the same and the position of the childnode needs to be the first position it is found in.
I know the name of the childNode1 before hand.

<parentNode>
  <childnode1 att1="1" att2="2"/>
  <childnode2></childnode2>
  <childnode21></childnode21>
  <childnode22></childnode22>
  <childnode23></childnode23>
  <childnode24></childnode24>
  <optionalNode></optionalNode>
</parentNode>

Is this even possible?
How should i go about it.
Thank you

Recommended Answers

All 2 Replies

Member Avatar for gravyboat

Here is an XSLT that will do what you want.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
    	<parentNode>
	    	<xsl:copy-of select=".//childnode1[1]"/>
	    	
	    	<xsl:for-each select="./parentNode/child::*[not(name()='childnode1')]">
	    		<xsl:copy-of select="."/>
	    	</xsl:for-each>
	    </parentNode>
	</xsl:template>

</xsl:stylesheet>

At the root we create the <parentNode> that will contain all children. Since we only want one childnode1, we copy the first by using the "[1]" position argument. We then loop through all of the children of parentNode, copying only those that are not named childnode1.

Thank you. This really Helped.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.