How to Transform XML Using XSLT And Deserialize The Result Using C#



TODO:

Have you ever wanted to load an XML Document, transform it using XSLT, and conver the result into a Class object?  This is handly so that you could take XML in various formats, use XSLT to transform it, and load it into Classes that your system knows about.

 

SOLUTION:

Dog myDog = new Dog();
XmlSerializer xmlSerial = new XmlSerializer(typeof(Dog));   //create the xmlserializer for class Dog
XmlDocument myXMLDocument = new XmlDocument();              //create the xml document
StringBuilder output = new StringBuilder();                 //create the string builder for the output
XslCompiledTransform myXslTrans = new XslCompiledTransform();  //create the xsl obj for transformation
XmlWriterSettings writerSettings = new XmlWriterSettings();    //create the writer settings object, as we want to omit XML declaration
writerSettings.OmitXmlDeclaration = true;                      //now set the omit flag to true
myXMLDocument.Load(@"c:\DogInput.xml");

//load xslt file
myXslTrans.Load(xsltfile);

//create an xmlwriter of out data
using (XmlWriter transformedData = XmlWriter.Create(output, writerSettings))
{
     //transform the document
     myXslTrans.Transform(myXMLDocument, transformedData);

     //now turn the string builder into an obj
     using (StringReader xmlString = new StringReader(output.ToString()))
     {
          myDog = (Dog)(xmlSerial.Deserialize(xmlString));
     }
}

 

NOTES:

Dog is a class i created to illustrate this task, you will put your classname in place of it.  The variable "xsltfile" is the path to your XSLT file.



Comments (2) -

Azi
Azi
3/11/2012 9:02:23 PM #

Hi Kilimanjaro,

Thank you  for your great post.
I have tried to follow the steps you have mentioned above but I’ve received the following error:

The Root Element is missing!


Could you please post your XLST and Dog Class? So I can compare my code with yours.

Regards,
Azi

Donnie Wishard
Donnie Wishard
3/29/2012 9:52:34 PM #

Here you go, this is the Dog Class, and the XML is below too, hopefully this will solve the issue.

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevelopersAlley
{
    [Serializable()]
    public class Dog
    {
        [XmlElement("Name")]
        public string Name { get; set; }

        [XmlElement("Breed")]
        public string Breed { get; set; }
    }
}


Here is the XML input:
<Dog>
     <Name>Tank</Name>
     <Breed>Boxer</Breed>
</Dog>

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading