StringBuilder or XMLDocument?

I wrote a console application to fetch some information from a web server, convert it to XML, and save it. I manually created XML (add a line using StringBuilder

). Since XML can be very large, is it better to use a class StringBuilder

or XMLDocument

etc. As far as memory is concerned? To be precise, my question is, if XML is like 10MB text, is it good to use memory with memory StringBuilder.append("")

or System.XML

?

I think a more efficient way would be to use StringBuilder, but save the XML to a file on HD after each iteration and clean up the stringbuilder object. Any comments? Thank you in advance.:)

+3


source to share


3 answers


Neither; I would use XmlWriter

:

using(var file = File.Create(path))
using(var writer = XmlWriter.Create(file))
{
  // write to writer here
}

      



This avoids the need to buffer a lot of data in memory to be executed both StringBuilder

and XmlDocument

and it avoids all the encoding issues that you run into when creating the xml manually (not a good idea to be honest).

+10


source


I would not create manually the XML using StringBuilder

, there is too much room for errors (if it is correct string escaping).



To write a larger XML file, you must use the XmlWriter class .

+5


source


If you have XSD for XML, I would use xsd.exe XML Schema Definition Tool that can generate C # classes.
It's pretty easy to serialize and deserialize XML from code so that you don't have to work with long strings this way. Just create your class and save it as valid XML text.

0


source







All Articles