Reputation: 51
I have a strangely formatted XML document which features a few tags that repeat; but I need to process this data using a tool that doesn't support repeated tags.
Thus I need a way to concatenate the data within the repeated tags.
My initial document appears as follows:
<root>
<irrelevantTag1>irrelevantData1</irrelevantTag1>
<irrelevantTag2>irrelevantData2</irrelevantTag2>
<irrelevantTag3>
<irrelevantTag4>irrelevantData4</irrelevantTag4>
<keyword>one</keyword>
<keyword>two</keyword>
</irrelevantTag3>
<irrelevantTag5>irrelevantData5</irrelevantTag5>
</root>
I need a stylesheet to concatenate the values with the two "keyword" tags and produce a single keyword tag as in the following output:
<root>
<irrelevantTag1>irrelevantData1</irrelevantTag1>
<irrelevantTag2>irrelevantData2</irrelevantTag2>
<irrelevantTag3>
<irrelevantTag4>irrelevantData4</irrelevantTag4>
<keyword>one,two</keyword>
</irrelevantTag3>
<irrelevantTag5>irrelevantData5</irrelevantTag5>
</root>
Upvotes: 4
Views: 480
Reputation: 2257
These two templates should do the trick:
<xsl:template match="keyword[1]">
<keyword>
<xsl:for-each select="../keyword">
<xsl:if test=". != ../keyword[1]">,</xsl:if>
<xsl:value-of select="."/>
</xsl:for-each>
</keyword>
</xsl:template>
<xsl:template match="keyword"/>
Use an apply-templates on a match for the parent element, or simply plug them into an identity transform.
Upvotes: 4