Thorin Oakenshield
Thorin Oakenshield

Reputation: 14682

How to add Process Instruction to an XML file in C#

How can I add a process instruction to ~50 xml files?

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

If I append the node, it is added to the end of the file but it needs to be first.

Upvotes: 1

Views: 2627

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500893

I would use LINQ to XML:

using System;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        var proc = new XProcessingInstruction
            ("xml-stylesheet", "type=\"text/xsl\" href=\"Sample.xsl\"");
        doc.Root.AddBeforeSelf(proc);
        doc.Save("test2.xml");
    }
}

Upvotes: 5

Related Questions