user3010912
user3010912

Reputation: 391

Create elements in target XML using data from source XML as element name using XSLT

My source XML contains both data and "metadata", describing the target XML.
Source data is a generic collection of entries (fields) and my goal is to create an XML with specific tag names.
Is it possible to convert the source below into target using XSLT?

Source:

<section>
   <name>TaxpayerInfo</name>
   <field>
       <name>firstName</name>
       <value>John</value>
  </field>
  <field>
       <name>lastName</name>
       <value>Smith</value>
  </field>
 </section>

Target

 <taxpayerInfo>   
   <firstName>John</firstName>    
   <lastName>Smith</lastName> 
 </taxpayerInfo>

Upvotes: 2

Views: 394

Answers (2)

Marvin Smit
Marvin Smit

Reputation: 4108

You can try the following XSLT (1.0).

It assume's the 'section' element in your original document will be the definition of the elements you want.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

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

  <xsl:template match="section">
    <xsl:variable name="fieldName" select="name" />

    <xsl:element name="{$fieldName}">
      <xsl:apply-templates select="field"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="field">
    <xsl:variable name="fieldName" select="name" />
    <xsl:element name="{$fieldName}">
      <xsl:value-of select="value"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Using this xslt against your example XML gave me the following result

<?xml version="1.0" encoding="utf-8"?>
<TaxpayerInfo>
  <firstName>John</firstName>
  <lastName>Smith</lastName>
</TaxpayerInfo>

Hope this helps,

Upvotes: 1

PhillyNJ
PhillyNJ

Reputation: 3903

Give this a try:

<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:template match="/">
        <xsl:element name="taxpayerInfo">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="section">
        <xsl:apply-templates/>
    </xsl:template>
    <xsl:template match="field[position() = 1]">
        <xsl:element name="firstName">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="field[position() = 2]">
        <xsl:element name="lastName">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="name"/>
</xsl:stylesheet>

Upvotes: 0

Related Questions