XSL Name Value Pair transformation

2019-08-03 04:53发布

问题:

I am not sure it's even possible but here it goes.

From this 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>

I am looking to convert it to the following using XSL transformation:

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

I can get the attribute names but not sure how to form the XML. Here's what I tried.

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

Which give me:

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

So, is it possible to do what I am looking for? Any help? Thanks

回答1:

This should do it:

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

When run on your sample data, the result is:

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