Transform reports to CSV using XSLT

The following XSLT stylesheet is a fairly simple transformation allowing to convert XML metric reports to CSV format (the columns do not have a fixed length, instead of a “,” char is used as the delimiter). The CSV columns have the following order: Module, Namespace, Type, Member, Maintainability Index, Cyclomatic Complexity, Class Coupling, Depth of Inheritance, Lines of Code.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

  <xsl:output method="text" indent="no" encoding="utf-8" />
  <xsl:strip-space elements="*" />

  <xsl:template match="/">

  <xsl:template name="MetricValues">
    <xsl:variable name="v1" select="./Metric[@Name = 'MaintainabilityIndex']/@Value" />
    <xsl:variable name="v2" select="./Metric[@Name = 'CyclomaticComplexity']/@Value" />
    <xsl:variable name="v3" select="./Metric[@Name = 'ClassCoupling']/@Value" />
    <xsl:variable name="v4" select="./Metric[@Name = 'DepthOfInheritance']/@Value" />
    <xsl:variable name="v5" select="./Metric[@Name = 'LinesOfCode']/@Value" />
    <xsl:variable name="s" select="concat($v1, ',', $v2, ',', $v3, ',', $v4, ',', $v5)" />
    <xsl:value-of select="$s" />

  <xsl:template match="Metrics">
    <xsl:variable name="moduleName" select="ancestor::Module/@Name" />
    <xsl:variable name="namespaceName" select="ancestor::Namespace/@Name" />
    <xsl:variable name="typeName" select="ancestor::Type/@Name" />
    <xsl:variable name="memberName" select="ancestor::Member/@Name" />
    <xsl:variable name="s" select="concat($moduleName, ',', $namespaceName, ',', $typeName, ',', $memberName, ',')" />
    <xsl:if test="$moduleName != ''">
      <xsl:value-of select="$s" />
    <xsl:call-template name="MetricValues" />

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s