Home > Blockchain >  XSLT - Form individual entries together in a group
XSLT - Form individual entries together in a group

Time:09-22

I'm relatively new to XSLT.

I'm trying to group individual XML entries with different names into a group, but all my previous attempts have failed.

Is that even possible or does XSLT reach its limits?

This is my input:

<DATA>
   <NAME_TO>abc_1</NAME_TO>
   <ZIP_TO>abc_1</ZIP_TO>
   <CITY_TO>abc_1</CITY_TO>
   <STREET_TO>abc_1</STREET_TO>
   <NAME_CARR>abc_2</NAME_CARR>
   <ZIP_CARR>abc_2</ZIP_CARR>
   <CITY_CARR>abc_2</CITY_CARR>
   <STREET_CARR>abc_2</STREET_CARR>
</DATA>

This should be my output:

<PARTNERS>
   <PARTNER>
      <PART>TO</PART>
      <NAME>abc_1</NAME>
      <ZIP>abc_1</ZIP>
      <CITY>abc_1</CITY>
      <STREET>abc_1</STREET>
   <PARTNER>
   <PARTNER>
      <PART>CARR</PART>
      <NAME>abc_2</NAME>
      <ZIP>abc_2</ZIP>
      <CITY>abc_2</CITY>
      <STREET>abc_2</STREET>
   <PARTNER>
<PARTNERS>

CodePudding user response:

How about simply:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/DATA"> 
    <PARTNERS>
        <PARTNER>
            <PART>TO</PART>
            <xsl:apply-templates select="*[contains(name(), '_TO')]"/>
        </PARTNER>
        <PARTNER>
            <PART>CARR</PART>
            <xsl:apply-templates select="*[contains(name(), '_CARR')]"/>
        </PARTNER>
    </PARTNERS>
</xsl:template> 

<xsl:template match="*"> 
    <xsl:element name="{substring-before(name(), '_')}">
        <xsl:value-of select="." />
    </xsl:element>
</xsl:template> 

</xsl:stylesheet>

P.S. You could make this generic by grouping the elements by substring-after(name(), '_').

  • Related