tags:

views:

30

answers:

1

How to add process instruction to an xml file after creating it.

My application has more than 50 xml file ...

i need to add Process Instruction to each file.

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

If i append the node it is added to the end of the file.

How to add it as the first node of the file

Please help me to do this

Thanks in advance

+2  A: 

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");
    }
}
Jon Skeet
@ Jon Skeet : Thank You....
Pramodh
I think your solution is just fine, but for the record, if we needed to do this for a large number of large files, we'd want to avoid the DOM entirely, so the right way would be to loop an XmlReader/XmlWriter pair. If speed were absolutely vital, we could ignore the whole XML issue by treating this as a text file insertion. However, I can't recommend this due to the risk of messing up the parsing and ruining the XML.
Steven Sudit
@Steven: Even for a lot of files, I wouldn't use XmlReader/XmlWriter until I'd found there was an actual problem. While they'd be more efficient, they'd also be more complex. This code simplicity itself, and even for a large number of large files, if the situation is a batch process or something else where raw efficiency isn't actually that important, I'd still go with the simplest solution.
Jon Skeet
@Jon: Like I said, I think the XDocument solution is just fine here. My goal was to point out alternatives that, while not as easy to code and therefore not our first choice, can handle stricter performance and scaling requirements. For example, I've had cases where I needed to replace an element in a large XML document while streaming it through, where buffering the whole document would have forced the client to wait for the first char until after I received the last. Likewise, if the doc is too
Steven Sudit
big to comfortably fit in memory, the reader/writer makes sense. In short, it's the "official right answer" that's too much trouble to be worth it in most cases but is always in reserve as the big hammer. :-)
Steven Sudit
@Steven: Yup, that all sounds reasonable. I think my argument was more that the files have to be *prohibitively* large, basically - just having a lot of files or those files being large isn't enough of a reason to go to the more complex case, by default :)
Jon Skeet
@Jon: If you continue being reasonable, I will find myself entirely unable to disagree with you. Please cut it out.
Steven Sudit