简体   繁体   中英

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 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 this 'generic' I want to convert the fields to some kind of key / value pair structure with an 1.0 XSL transformation.

Example required XML:

<?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>

I've found an article which describes it the other way around XSLT: Convert Name/Value pair and transform an XML

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>
<xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Products">
        <xsl:copy>
            <xsl:for-each select="Product">
                <Product>
                    <xsl:for-each select="./*">
                        <Var>
                            <VarName><xsl:value-of select="local-name()"/></VarName>
                            <VarValue><xsl:value-of select="."/></VarValue>
                        </Var>
                    </xsl:for-each>
                </Product>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM