How to convert a XML file based on attributes to an XML file based on child nodes by using XSLT.

I wanted to convert a XML based on attributes to a XML based on child nodes, e.g.:

 

Input

<?xml version="1.0" encoding="utf-8" ?> <people> <person firstname="John" lastname="Smith"/> <person firstname="Michael" lastname="Johnson"/> <person firstname="Jacob" lastname="Williams"/> </people>

Output

<people>
  <person>
    <firstname>John</firstname>
    <lastname>Smith</lastname>
  </person>
  <person>
    <firstname>Michael</firstname>
    <lastname>Johnson</lastname>
  </person>
  <person>
    <firstname>Jacob</firstname>
    <lastname>Williams</lastname>
  </person>
</people>

XSLT

The forum post [http://stackoverflow.com/questions/6496334/c-sharp-to-convert-xml-attributes-to-elements] contains a XSLT script that will just do that.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="http://www.something.com">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:variable name="vNamespace" select="namespace-uri(/*)"/>

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

  <xsl:template match="*/*/@*">
    <xsl:element name="{name()}" namespace="{$vNamespace}">
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="x:Value">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
    <xsl:apply-templates select="@*"/>
  </xsl:template>
</xsl:stylesheet>

Transforming an input file to an output file in C#, by using XSLT.

Just a code snippet for transforming an input file to an output file in C# by using XSLT:

/// <summary>
/// Transform an input file to an output file, by using XSLT.
/// </summary>
public void ExecuteTransform()
{
    string xsltFilePath = @"C:\BDATA\Transform.xsl";
    string sourceFilePath = @"C:\BDATA\input.xml";
    string destinationFilePath = @"C:\BDATA\output.xml";

    var transform = new XslCompiledTransform();
    transform.Load(xsltFilePath);
    transform.Transform(sourceFilePath, destinationFilePath);
}

Generating a HTML link <A>, with href attribute

There are 2 ways to generate a HTML <A> link with XSLT:

 

Using the <xsl:element>

        <xsl:element name="a">
            <xsl:attribute name="href">
                <xsl:value-of select="url"/>
            </xsl:attribute>
            <xsl:value-of select="url"/>
        </xsl:element>

Using only text

<a href="{url}"><xsl:value-of select="url"/></a>

 

HTML link, that fires a JavaScript function with parameter

<xsl:element name="a">
   <xsl:attribute name="href">javascript:myFunction(<xsl:value-of select="@parameter1"/>);</xsl:attribute>
      My link text
</xsl:element>