Thursday, July 12, 2012

C# XML Transformation using XSLT


If you have one type of XML and need to transform it to another type, then you can use XSLT for that purposes. For instance in the health care field, there are a lot of XML standards, such as CCD, CCR etc. Sometimes one type of XML need to be transformed to another one. The best way to do it is to use XSLT. You may ask where do you get appropriate XSLT for specific XML transformation? Well, for example I use Altova MapForce. MapForce allows you to do XML transformation manually by simply dragging appropriate attributes. Once you done with that, MapForce will generate an XSLT which you can use then in your code.
Altova MapForce XML Transformation and XSLT Generation
Ok, we got an XSLT file, here is how we use it in C# code in order to transform XML file:

class Program
{
    static void Main(string[] args)
    {
        TransformXML("XML.xml", "XMLtoCCD.xslt");
    }

    public static void TransformXML(string sXmlPath, string sXslPath)
    {
        try
        {
            /* loading XML */
            XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
            XslCompiledTransform myXslTrans = new XslCompiledTransform();
            /* loading XSLT */
            myXslTrans.Load(sXslPath);
            /* creating Output Stream */
            XmlTextWriter myWriter = new XmlTextWriter("result.xml", null);
            /* XML transformation */
            myXslTrans.Transform(myXPathDoc, null, myWriter);
            myWriter.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e.ToString());
        }
    }
}
That's it! If you have any questions, please ask, I'll be happy to help.

5 comments:

  1. Hello, Maybe you have heard about family.show program. So I want that program to show a personal from my company. So I have a database in MSSQL, I crateded a Webservise which can show the personal as hierarchical (like genealogical family). The web services store data as xml, so I want to input that data to the family.show program, which is also using xml based document. Please give an advise how to realize it. Thank you.

    ReplyDelete
  2. Hi, Abdulyar.
    If you need to read data from XML into business objects than I suggest to read this post: http://www.codearsenal.net/2012/07/c-sharp-load-xml-using-xlinq.html

    ReplyDelete
  3. How can I iterate over a Directory structure with various Folders having Xml files and write newly generated files onto the output Directory structures. If you can provide solution that will be a great help.

    ReplyDelete