将xml字段转换为键/值对

时间:2019-04-30 11:35:28

标签: xslt xslt-1.0

在SAP PI中,我有来自REST服务(Web配置器)的xml文件,其字段可能因产品而异。例如,产品A具有颜色,高度和宽度,产品B具有颜色,高度,宽度和深度。

传入XML示例:

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

要处理此“泛型”,我想通过1.0 XSL转换将字段转换为某种键/值对结构。

示例必需的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>

我找到了一篇描述它的文章 XSLT: Convert Name/Value pair and transform an XML

2 个答案:

答案 0 :(得分:1)

这是马丁告诉你的:

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

答案 1 :(得分:1)

<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>
相关问题