如何在C#中将处理指令添加到XML文件

Tho*_*eld 1 c# xml

如何为~50 xml文件添加进程指令?

 <?xml-stylesheet type="text/xsl" href="Sample.xsl"?> 
Run Code Online (Sandbox Code Playgroud)

如果我追加节点,它会被添加到文件的末尾,但它必须是第一个.

Jon*_*eet 5

我会使用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");
    }
}
Run Code Online (Sandbox Code Playgroud)