Search code examples
xmlxsltxslt-1.0xslt-2.0

Getting the element name and printing it out


I have an XML file with elements and element names.

I would like to transmute the element names as an element and fill these elements with the matching content of the input elements.

The sticking point is that I try this dynamically. The whole thing to do Static I already have the process of the back-end is dynamic. Say the input is dynamic.

Input example:

<Parameter name="customer">customer</Parameter>
<Parameter name="Date">Date</Parameter>
<Parameter name="Budgetnumber">Budgetnumber</Parameter>
<Parameter name="External">External</Parameter>
<Parameter name="Target">Target</Parameter>
<Parameter name="Worker">Worker</Parameter>
<Parameter name="customer_number">1234567890</Parameter>
<Parameter name="DataPath">Data/Path/</Parameter>
<Parameter name="DUMMY">DUMMY</Parameter>
<Parameter name="FileName">File.Name</Parameter>
<Parameter name="document_number">123123</Parameter>

My "bad" XSLT mapping:

<parameter>
    <xsl:for-each select="./*/Parameter">
        <xsl:value-of select="local-name(.)"/> : <xsl:value-of select="."/>
    </xsl:for-each> 
</parameter>

I am not the best in XSLT so I hoped some one can help me to get the following example output:

<parameter>
   <customer>customer</customer>
   <Date>Date</Date>
   <Budgetnumber>Budgetnumber</Budgetnumber>
   <External>External</External>
   <Target>Target</Target>
   <Worker>Worker</Worker>
   <customer_number>1234567890</customer_number>
   <DataPath>Data/Path/</DataPath>
   <DUMMY>DUMMY</DUMMY>
   <FileName>File.Name</FileName>
   <document_number>123123</document_number>
</parameter>

Solution

  • Here's how you should construct your xslt.

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" indent="yes"/>   
    
        <xsl:template match="/">
          <parameter>
            <xsl:for-each select="Parameter">           
                <xsl:element name="{@name}">
                    <xsl:value-of select="text()" />
                </xsl:element>
            </xsl:for-each>
          </parameter>
        </xsl:template>    
    </xsl:stylesheet>