1

I have XML that I need to convert to a more simplified format. I am sure this can be done with XSLT, but I am unsure how.

I need to convert:

<Fields>
  <Field>
    <Name>Element1</Name>
    <Value>Value 1</Value>
  </Field>
  <Field>
    <Name>Element2</Name>
    <Value>Value 2</Value>
  </Field>
</Fields>

into

<Fields>
  <Element1>Value 1</Element1>
  <Element2>Value 2</Element2>
</Fields>

This is what I have currently:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:copy-of select="Fields/Field/*"/>
      <xsl:apply-templates select="*[name()]"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

1 Answer 1

1

Your input XML,

<Fields>
  <Field>
    <Name>Element1</Name>
    <Value>Value 1</Value>
  </Field>
  <Field>
    <Name>Element2</Name>
    <Value>Value 2</Value>
  </Field>
</Fields>

transformed by this XSLT,

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="Field">
    <xsl:element name="{Name}">
      <xsl:value-of select="Value"/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

yields this output XML,

<?xml version="1.0" encoding="UTF-8"?>
<Fields>
  <Element1>Value 1</Element1>
  <Element2>Value 2</Element2>
</Fields>

as requested.

Sign up to request clarification or add additional context in comments.

2 Comments

Important notice: There are rules for valid xml element names. (1) Names must not begin with a digit. (2) Names cannot start with special characters such as a hyphen or period. (3) Names cannot contain special characters other than the period, hyphen, underscore, and colon.
You can prevent invalid names to an extent with the double translate method- <xsl:element name="{translate(Name, translate(Name, $validChars, ''), '')}"/>, where $validChars is a variable containing all characters you want to allow in a name. This is a bit crude though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.