Reputation: 97
I have a requirement to select same element came 2nd time in the same parent element using xslt.
I am displaying my xml..
<parent>
<a>0001</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f></f>
<g></g>
<h></h>
<i></i>
<a>0002</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f></f>
<g></g>
<h></h>
<i></i>
</parent>
In my xml , a , b, c and all other elements came twice . So If I have to fetch value of element which came 2nd time in XSLT then could any1 please tell me how to do this?
Upvotes: 0
Views: 104
Reputation: 1278
Try this to identify same element (name, not the content) appearing twice within same parent:
Input XML:
<parent>
<a>0001</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f></f>
<g></g>
<h></h>
<i></i>
<a>0002</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f></f>
<g></g>
<h></h>
<i></i>
<j>New element</j>
</parent>
XSLT 1.0:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kDuplicate" match="*[generate-id(parent::*) =
generate-id(current()/parent::*)]" use="name()"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()[key('kDuplicate', name())[2]]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="parent">
<xsl:copy>
<xsl:for-each select="descendant::*[key('kDuplicate', name())[2]]">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Result: (element j
not appearing, as it is appearing only once within its parent)
<parent>
<a>0001</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f/>
<g/>
<h/>
<i/>
<a>0002</a>
<b>05</b>
<c>20160825</c>
<d>9463</d>
<e>anders skov petersen</e>
<f/>
<g/>
<h/>
<i/>
</parent>
Upvotes: 0
Reputation: 1676
You can access the second a with the following XPath-Expression
/parent/a[2]
This is the short form of
/parent/a[position()=2]
See https://www.w3.org/TR/xpath/
Upvotes: 1