tags:

views:

215

answers:

1

Hi,

Is it possible in C# is append an XElement to an already existing xml file, without saving the whole xml, but just the new element?

So i don't want something like this, since it will write the whole xml to disk.

XDocument document = new XDocument();
document.Load("filename");
document.Root.add(new XElement("name", "content"));
document.save("filename");

thanks in advance.

+2  A: 

Yes, but only by getting a bit more low level than in your example.

In an XML file you can only have one root element, so if you simply append to the file to add a new element, you will create a broken XML file.

However, you could read from the end of the file and parse it to find the start of the root element's end-tag (which would give you a file Position). Then you could open the file as a FileStream for writing, set the write Position to the start of the root-end-tag, and then write your new element to the stream as normal. Then you'd have to complete the file "manually" by appending text to add a new root-end-tag.

Jason Williams
I see, so this is the only way to do what I am asking? there isn't a simpler (1 magic call) to do it ?
Spi1988
Not if you want to avoid re-writing the entire file. (It's possible there is a weird .net thing somewhere that might allow you to do something like this, but highly unlikely)
Jason Williams