xsltxslt-1.0sap-pisap-xi

Transform XML fields to key/value pairs in PI XSLT mapping


In SAP PI, I have xml files from rest services (web configurator) for which the fields can vary based on the product. For instance product A has a color, a height and a width, and product B has a color, a height, a width and a depth.

Example of incoming XML:

<?xml version="1.0" encoding="UTF-8"?>
<Order>
    <Products>
        <Product> 
            <Color>Black</Color>
            <Height>2000</Height>
            <Width>1000</Width>
        </Product>
    </Products>
</Order>

To handle these varying elements, I want to convert the fields to some kind of key / value pair structure with an XSL 1.0 transformation.

Example of what I'd like to obtain:

<?xml version="1.0" encoding="UTF-8"?>
<Order>
    <Products>
        <Product> 
            <Var>
                <VarName>Color</VarName>
                <VarValue>Black</VarValue>
            </Var>
            <Var>
                <VarName>Height</VarName>
                <VarValue>2000</VarValue>
            </Var>
            <Var>
                <VarName>Width</VarName>
                <VarValue>1000</VarValue>
            </Var>
        </Product>
    </Products>
</Order>

NB: this article describes the other way around: XSLT: Convert Name/Value pair and transform an XML.


Solution

  • This is what Martin told you:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.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="Product/*">
        <Var>
          <VarName>
            <xsl:value-of select="name()"/>
          </VarName>
          <VarValue>
            <xsl:value-of select="."/>
          </VarValue>
        </Var>
      </xsl:template>
    
      <xsl:template match="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:template>
    
    </xsl:stylesheet>