首页 > 解决方案 > XML 输出,元素值作为标签名称,下一个后续元素值作为创建标签的值

问题描述

我需要形成一个输出 xml,其中我需要将字段值作为标签,然后将后续的下一个字段值作为创建标签的值。

<PrimaryKey>
    <PK1FeildName>CONNO</PK1FeildName>
    <PK1Value>001</PK1Value>
    <PK2FeildName>INNO</PK2FeildName>
    <PK2Value>123</PK2Value>
    <PK3FeildName>CONNO</PK3FeildName>
    <PK3Value>011</PK3Value>
</PrimaryKey>

预期输出:

<PrimaryKey>
  <CONNO>001</CONNO>
  <INNO>123</INNO>
  <CONNO>011</CONNO>
</PrimaryKey>

标签: xsltibm-integration-busextended-sql

解决方案


如果我们认为元素总是成对出现,其中第一个元素的值是标签名称,第二个元素是值,那么这样可以:

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

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="PrimaryKey">
      <xsl:element name="PrimaryKey">
          <xsl:apply-templates/>
      </xsl:element>
  </xsl:template>

  <xsl:template match="*">
    <xsl:if test="count(preceding-sibling::*) mod 2 = 0">
        <xsl:element name="{.}">
            <xsl:value-of select="following-sibling::*[1]"/>
        </xsl:element>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

你可以在这里试试:https ://xsltfiddle.liberty-development.net/bwdws3

编辑以回答评论

示例 XML:

<Document>
    <PrimaryKey>
        <PK1FeildName>CONNO</PK1FeildName>
        <PK1Value>001</PK1Value>
        <PK2FeildName>INNO</PK2FeildName>
        <PK2Value>123</PK2Value>
        <PK3FeildName>CONNO</PK3FeildName>
        <PK3Value>011</PK3Value>
    </PrimaryKey>
    <PrimaryKey>
        <PK1FeildName>CONNO2</PK1FeildName>
        <PK1Value>0012</PK1Value>
        <PK2FeildName>INNO2</PK2FeildName>
        <PK2Value>1232</PK2Value>
        <PK3FeildName>CONNO2</PK3FeildName>
        <PK3Value>0112</PK3Value>
    </PrimaryKey>
</Document>

修改后的 XSLT:

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

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
      <xsl:element name="PrimaryKey">
          <xsl:apply-templates/>
      </xsl:element>
  </xsl:template>

  <xsl:template match="PrimaryKey/*">
    <xsl:if test="count(preceding-sibling::*) mod 2 = 0">
        <xsl:element name="{.}">
            <xsl:value-of select="following-sibling::*[1]"/>
        </xsl:element>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/bwdws3/1


推荐阅读