DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   XML, XSLT and XPATH (http://www.daniweb.com/forums/forum134.html)
-   -   new to xslt (http://www.daniweb.com/forums/thread152706.html)

nnobakht Oct 21st, 2008 4:36 pm
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

gravyboat Oct 27th, 2008 2:38 pm
Re: new to xslt
 
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.

nnobakht Oct 28th, 2008 3:30 pm
Re: new to xslt
 
Thank you. This really Helped.


All times are GMT -4. The time now is 9:24 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC