1

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
  • Exactly what do you want to save?
    – Welbog
    Jan 15, 2010 at 19:28
  • I would like to append the XElement to the xml file. Just like Jason Williams wrote in the next post :)
    – PB_MLT
    Jan 15, 2010 at 19:34

1 Answer 1

2

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.

2
  • 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 ?
    – PB_MLT
    Jan 15, 2010 at 19:36
  • 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) Jan 15, 2010 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.