XSL名称值对转型(XSL Name Value Pair transformation)

2019-09-30 06:50发布

我不知道它甚至有可能,但在这里不言而喻。

从这个XML:

<?xml version="1.0" encoding="UTF-8"?>
<AttributesCollection>
    <Attributes>
        <AttributeName>AAA</AttributeName>
        <AttributeValue>Value1</AttributeValue>
    </Attributes>
    <Attributes>
        <AttributeName>BBB</AttributeName>
        <AttributeValue>Value2</AttributeValue>
    </Attributes>
</AttributesCollection>

我期待将其转换为以下使用XSL转换:

<Attributes>
   <AAA>Value1</AAA>
   <BBB>Value2</BBB>
</Attributes>

我能得到的属性名称,但不知道如何形成的XML。 下面是我试过了。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:for-each select="./AttributesCollection/Attributes/AttributeName">
            Name:<xsl:value-of select="."/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

这给我:

<?xml version="1.0" encoding="UTF-8"?>
            Name:AAA
            Name:BBB

那么,是不是可以做什么,我找? 任何帮助吗? 谢谢

Answer 1:

这应该这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/*">
    <Attributes>
      <xsl:apply-templates select="Attributes" />
    </Attributes>
  </xsl:template>

  <xsl:template match="Attributes">
    <xsl:element name="{AttributeName}">
      <xsl:value-of select="AttributeValue" />
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

当你的样本数据运行,其结果是:

<Attributes>
  <AAA>Value1</AAA>
  <BBB>Value2</BBB>
</Attributes>


文章来源: XSL Name Value Pair transformation