Home > database >  Extracting element-name from xml input in xslt
Extracting element-name from xml input in xslt

Time:09-08

I have an XML input that looks like this:-

<root>
  <type>abc</type>
  <data>
    <attributes>
      <atr1>
        <values>val1</values>
      </atr1>
      <atr2>
        <values>val2</values>
      </atr2>
      . .
    </attributes>
  </data>
</root>

the attributes child node (atr1,atr2..or even xyz.) can be any value and hence want to extract the name of the child node dynamically and then output it as an xml element only.

my xslt right now looks like this:-

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" method="xml" omit-xml-declaration="yes" />
  <xsl:template match="/">
    <root>
      <type>
        <xsl:value-of select="root/type" />
      </type>
      <Attributes>
        <xsl:for-each select="root/data/attributes">
          <Attribute>
            <xsl:attribute name="id">
              <xsl:value-of select="name(.)" />
            </xsl:attribute>
            <values>
              <xsl:value-of select="attributes/values/value" />
            </values>
          </Attribute>
        </xsl:for-each>
      </Attributes>
    </root>
  </xsl:template>
</xsl:stylesheet>

whats the right way to extract the element-name of 'attributes' child nodes?

i want my output xml structure to look like this:-

<root>
  <type />
  <attributes>
    <atr1><value /></atr1>
    <atr2><value /></atr2>
    . . .
  </attributes>
</root>

CodePudding user response:

You can process all child elements with * (e.g. root/data/attributes/*) and then of course use name() or local-name() to read out the name of the currently processed child element.

CodePudding user response:

extract the name of the child node dynamically and then output it as an xml element only.

The same effect can be produced simply by doing a shallow copy:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates select="*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="data">
    <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>
  • Related