Combining duplicate tags using XSL

I have a strangely formatted XML document in which there are several tags that are repeated; but I need to process this data with a tool that does not support duplicate tags.

So I need a way to concatenate data in duplicate tags.

My original document is 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 combine the values ​​with two "keyword" tags and create a single keyword tag, as in the next release:

 <root> <irrelevantTag1>irrelevantData1</irrelevantTag1> <irrelevantTag2>irrelevantData2</irrelevantTag2> <irrelevantTag3> <irrelevantTag4>irrelevantData4</irrelevantTag4> <keyword>one,two</keyword> </irrelevantTag3> <irrelevantTag5>irrelevantData5</irrelevantTag5> </root> 
+4
source share
1 answer

These two patterns 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 the apply-template to match the parent element or just connect them to an identity transformation.

+4
source

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


All Articles