xml - Concatenate node values in XSLT -
i need concatenate values of xml based on following:
here xml:
<?xml version="1.0" encoding="utf-8"?> <root> <parent> <name>father 1</name> <child> <name>f1 - child 1</name> <age>2</age> </child> <child> <name>f1- child 2</name> <age>4</age> </child> </parent> <parent> <name>father 2</name> <child> <name>f2 - child 1</name> <age>2</age> </child> <child> <name>f2 - child 2</name> <age>4</age> </child> </parent> </root>
and here xslt:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match ="root"> <xsl:apply-templates select ="parent/name" /> <xsl:apply-templates select ="parent/child" /> </xsl:template> <xsl:template match ="parent/name"> <fathername> <xsl:value-of select ="."/> </fathername> </xsl:template> <xsl:template match ="parent/child"> <childnames> <xsl:for-each select="name"> <xsl:value-of select="." /> <xsl:if test="position()!=last()"> <xsl:text>, </xsl:text> </xsl:if> </xsl:for-each> </childnames> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
which results this
<?xml version="1.0" encoding="utf-8"?> <fathername>father 1</fathername> <fathername>father 2</fathername> <childnames>f1 - child 1</childnames> <childnames>f1- child 2</childnames> <childnames>f2 - child 1</childnames> <childnames>f2 - child 2</childnames>
but result need this:
<fathername>father 1</fathername> <childnames>f1 - child 1, f1- child 2</childnames> <fathername>father 2</fathername> <childnames>f2 - child 1, f2 - child 2</childnames>
can me result need?
essentially, need move line <xsl:apply-templates select ="parent/child" />
out of current template, , template matches parent/name
. this:
<xsl:template match="parent/name"> <fathername> <xsl:value-of select ="."/> </fathername> <childnames> <xsl:apply-templates select ="../child" /> </childnames> </xsl:template>
the ..
here go parent
node can select child nodes. note, don't need xsl:for-each
in template matching child.
actually, might easier match on parent
node parent/name
node.
try xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="root"> <xsl:apply-templates select="parent" /> </xsl:template> <xsl:template match="parent"> <fathername> <xsl:value-of select ="name"/> </fathername> <childnames> <xsl:apply-templates select ="child" /> </childnames> </xsl:template> <xsl:template match="child"> <xsl:if test="position()!=1"> <xsl:text>, </xsl:text> </xsl:if> <xsl:value-of select="name" /> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
Comments
Post a Comment