xmlformatextracttransform

How to extract values from a multi level XML and make them a new format


I've tried several posts but no success yet, I would like to change the format of the following tables (the levels keep going up to 100)


        <level val="1">
            <hp>94</hp>
            <mp>30</mp>
            <cp>37.6</cp>
            <hpRegen>2</hpRegen>
            <mpRegen>0.9</mpRegen>
            <cpRegen>2</cpRegen>
        </level>
        <level val="2">
            <hp>107.65</hp>
            <mp>35.46</mp>
            <cp>43.06</cp>
            <hpRegen>2</hpRegen>
            <mpRegen>0.9</mpRegen>
            <cpRegen>2</cpRegen>
        </level>
        <level val="3">
            <hp>121.45</hp>
            <mp>40.98</mp>
            <cp>48.58</cp>
            <hpRegen>3</hpRegen>
            <mpRegen>0.9</mpRegen>
            <cpRegen>2</cpRegen>
        </level>

and transform that to the following format (divided each level by semicolon):

        <set hpTable="94;107.65;121.45"/>
        <set mpTable="30;35.46;40.98"/>
        <set cpTable="37.6;43.06;48.58"/>
        <set hpRegenTable="2;2;3"/>
        <set mpRegenTable="0.9;0.9;0.9"/>
        <set cpRegenTable="2;2;2"/>

Thanks in advance.

Tried manual removing tags and transform, several python etree replace but most ended up in errors


Solution

  • In XSLT 2.0 or later:

    <xsl:for-each-group select="//level/*" group-by="name()">
      <set>
         <xsl:attribute name="{current-grouping-key()}Table"
                        select="string-join(current-group(), ';')"/>
      </set>
    </xsl:for-each-group>