Reputation: 13063
I want to change the root node and the namespace in an XML document programatically in C#. I've come across a couple of different solutions that mostly use XmlDocument
.
The most common solution is to load the entire document in memory, replace the rood node and then set the InnerXml
to the InnerXml
of the original root.
It seems a bit stupid to me to load an entire XML document in memory when all you need is exactly one node. This should work practically as fast for any size XML.
Example:
<MyDocument xmlns="http://question.stackoverflow.com">
<AfewKilobytesOfXML />
</MyDocument>
Could become:
<YourDocument xmlns="http://answer.stackoverflow.com">
<AfewKilobytesOfXML />
</YourDocument>
Best case is that the body of the document is completely ignored and isn't loaded in memory as more than just a stream.
I'd want to provide something I've tried but I don't even know which classes are the best to do this.
The input is a Stream
. Good to know: the Stream
might not contain XML at all, so bonus points if your answer has a check for that.
Upvotes: 1
Views: 1437
Reputation: 1697
If you want to avoid loading the entire xml file into memory, I would say take a look at XmlTextReader and XmlTextWriter. These classes are designed for processing XML files node by node without loading the whole document into memory.
See the various approaches being used in this link : http://www.codeproject.com/Articles/15278/How-to-Append-to-a-Large-XML-File
Upvotes: 2