XSLT select unique node

It drives me crazy for xlt newbies like me.

Input:

<root> <a><name>kyle</name></a> <b><name>stan</name></b> <b><name>wendy</name></b> <b><name>cece</name></b> </root> 

Expected Result:

 <root> <a><name>kyle</name></a> <b><name>stan</name></b> </root> 

I was asked to return the first unique node to "root", how to do this?

Either xslt 1.0 or 2.0 is fine.

Thank you very much!!!!

+4
source share
2 answers

XSLT 2.0 Solution:

 <?xml version="2.0" encoding="utf-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <root> <xsl:for-each-group select="root/*" group-by="local-name()"> <xsl:copy-of select="."/> </xsl:for-each-group> </root> </xsl:template> </xsl:stylesheet> 

Output:

 <?xml version="1.0" encoding="UTF-8"?> <root> <a> <name>kyle</name> </a> <b> <name>stan</name> </b> </root> 
+1
source

You can match any element that has a previous brother with the same name and not display anything.

XSLT Example:

 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="/*/*[preceding-sibling::*[name() = current()/name()]]"/> </xsl:stylesheet> 

Output (using Saxon 9 HE):

 <root> <a> <name>kyle</name> </a> <b> <name>stan</name> </b> </root> 
+1
source

Source: https://habr.com/ru/post/1382188/


All Articles