Wednesday, July 29, 2015

XSLT for converting DataSet to JSON

<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="text" indent="no" omit-xml-declaration="yes" />
  <xsl:template match="NewDataSet">
{
    "Jobs": [
        <xsl:apply-templates select="Table"/>
        {}
    ]
}
  </xsl:template>
 
  <xsl:template match="Table">
        {
            "id": "<xsl:value-of select="jobid"/>",
            "title": "<xsl:value-of select="jobtitle"/>",
            "location":{
                "address": "<xsl:value-of select="jobaddress"/>",
                "city": "<xsl:value-of select="jobcity"/>",
                "state": "<xsl:value-of select="jobstate"/>",
                "zip": "<xsl:value-of select="jobzip"/>"
            },
            "group": {
                "groupcode": "<xsl:value-of select="jobgroup"/>",
                "description": "<xsl:value-of select="jobgroupdescription"/>"
            },
            "otherinformation": "<xsl:value-of select="otherinformation"/>",
            "payload": "<xsl:value-of select="payload"/>"
                   
        },
    </xsl:template>

</xsl:stylesheet>

Convert XML format using XSLT

using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

public virtual Stream Transform(Stream payload)
{
    XPathDocument myXPathDoc = new XPathDocument(payload);
    XslCompiledTransform myXslTrans = new XslCompiledTransform();
    myXslTrans.Load(this.XsltPath); //Path to XSLT used for transform
    Stream formattedRequest = new MemoryStream();
    XmlTextWriter myWriter = new XmlTextWriter(formattedRequest, null);
    myXslTrans.Transform(myXPathDoc, null, myWriter);
    formattedRequest.Seek(0, SeekOrigin.Begin);

    payload.Close();
    return formattedRequest;    
}