Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first?

Tags:

c#

xml

I have a very basic XML structure/file on disk which is something like:

<root>
    <data timestamp="dd-mm-yyyy" type="comment">kdkdkdk</data>
    <data timestamp="dd-mm-yyyy" type="event">kdkdkdkgffgfdgf</data>
    <data timestamp="dd-mm-yyyy" type="something">kddsdsfsdkdkdk</data>
</root>

The XML will be, as mentioned, in an external file on disk. As the file might grow fairly large (actually gets 'trimmed' every couple of weeks), I don't want to load the XML file first to add a new node...

Is there a way to add a new node like this? it can be just added to the top/bottom etc, as the process that actually uses the XML sorts it by timestamp anyway..

I'm guessing a crude way is to append the node as text.. however I think that would add the node AFTER the end tag??

Any ideas gratefully received.. David.

like image 731
Dav.id Avatar asked Jan 23 '11 11:01

Dav.id


1 Answers

Not with any XML API or tool.

You could open the file as Text, find the Position of </root> and start overwriting from there. And of course add the </root> again.


A quick and dirty approach, this is not very robust:

  • make sure you prep the initial file, there should be nothing (no whitespace) after the closing tag
  • make sure you use ASCII or UTF8 encoding

====

string closeTag = "</root>";
int closeLength = Encoding.UTF8.GetBytes(closeTag).Length;

var fs = System.IO.File.Open(filename, System.IO.FileMode.Open);
fs.Position = fs.Length - closeLength;

var writer = new StreamWriter(fs);  // after the Position is set

writer.WriteLine(newTag);
writer.Write(closeTag);  // NOT WriteLine !!

writer.Close();
fs.Close();

And of course you know about using using() {} blocks.

like image 144
Henk Holterman Avatar answered Sep 28 '22 02:09

Henk Holterman