How to fix this xml node merging to keep all the unique attributes using xslt?

Jess

New Member
I have this input file:\[code\]<root> <library id="L1"> <shelf1 id="1"> <book id="1" action="borrow"> <attributes> <user>John</user> </attributes> <other1>y</other1> </book> <book id="1" action="extend"> <attributes> <user>Woo</user> <length>3</length> </attributes> <other2>y</other2> </book> <book id="1" action="extend"> <attributes> <length>2</length> <condition>ok</condition> </attributes> <other3>y</other3> </book> <book id="2" action="borrow">...</book> </shelf1> <shelf2>...</shelf2> </library></root>\[/code\]Expected output:\[code\]<root> <library id="L1"> <shelf1 id="1"> <book id="1" action="borrow"> <attributes> <user>Woo</user> <length>2</length> <condition>ok</condition> </attributes> <other1>y</other1> <other2>y</other2> <other3>y</other3> </book> <book id="2" action="borrow">...</book> </shelf1> <shelf2>...</shelf2> </library></root>\[/code\]My XSL:\[code\]<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="library/*/*[1]"> <xsl:copy> <xsl:apply-templates select="@*"/> <attributes> <xsl:for-each-group select="attributes/*" group-by="name()"> <xsl:sort select="current-grouping-key()"/> <xsl:apply-templates select="."/> </xsl:for-each-group> </attributes> <xsl:apply-templates select="*[not(self::attributes)]"/> </xsl:copy> </xsl:template> <xsl:template match= "library/*/* [@action='extend' and following-sibling::*[1][@action='extend'] or preceding-sibling::*[@action='borrow']]"/></xsl:stylesheet>\[/code\]For every node with \[code\]action=borrow\[/code\] followed by one or more node with \[code\]action=extend\[/code\]
  • Merge it together to the node with \[code\]action=borrow\[/code\].
  • Merge the \[code\]attributes\[/code\] children together such that it will have all the unique attributes from the siblings with the latest value.
  • leave other children unchanged
Please let me know how to fix this transformation using XSLT 2.0 ? Thanks very much. Kind regards,John
 
Back
Top