954,153 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

new to xslt

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

nnobakht
Light Poster
47 posts since Nov 2006
Reputation Points: 10
Solved Threads: 1
 

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

gravyboat
Newbie Poster
14 posts since Jun 2008
Reputation Points: 10
Solved Threads: 2
 

Thank you. This really Helped.

nnobakht
Light Poster
47 posts since Nov 2006
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You