Having an XML file point to an XSLT after serialization (or not)

So, you just serialized your data structure to an XML file and you want to have it always load with a transformation file – how do you do that? Sure, you can go manually open up each file and add the one line, but here’s a chunk of code I stumbled across that does it instead. This just briefly opens the file, inserts the missing line, then re-saves it.

In your XML, normally, you would add one line of XML to specify which transformation file to use when loading the file – so that when you attempt to view the XML, it will be formatted. Typically, that is something like this:

<?xml version="1.0" encoding="utf-8"?>

<?xml-stylesheet type="text/xsl" href="XSLTFile1.xslt"?>

<data xmlns="http://schemas.somecompany.com/2008/03/someApp">


    <customer firstName="John" lastName="Doe"/>



In code, here is how you would add that xml-stylesheet part:

    public static void ApplyXslt(Uri pathToXml, Uri pathToXslt)


        XmlDocument currentDocument = new XmlDocument();



        string styleSheetData = "type="text/xsl" href="" + pathToXslt.AbsoluteUri + """;


        XmlProcessingInstruction xsltInstruction = currentDocument.CreateProcessingInstruction("xml-stylesheet", styleSheetData);


        currentDocument.InsertAfter(xsltInstruction, currentDocument.FirstChild);





Posted in Uncategorized, XML stuff

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Enter your email address to follow this blog and receive notifications of new posts by email.

Join 9 other followers

%d bloggers like this: