What are the best functions, practices, and/or techniques to read/write XML with C#/.NET?
-
Found some related posts, too: http://stackoverflow.com/questions/220867/how-to-deal-with-xml-in-c http://stackoverflow.com/questions/41994/parsing-an-xml-file-in-c http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files-with-c -g – greg7gkb Jan 14 '09 at 18:42
5 Answers
If you are working with .NET 3.5, LINQ to XML is certainly a very good way to interact with XML.

- 14,268
- 17
- 76
- 108
There are classes to read XML:
XmlDocument
is slow and memory-intensive: it parses the XML and loads it into an in-RAM DOM, which is good if you want to edit it.XmlReader
is less memory-intensive: it scans the XML from front to back, never needing to keep all of it in RAM at once.
Similarly, for writing you can construct an XmlDocument
and then save it, or use an XmlWriter
.
After I wrote the above, there's now a new set of APIs which are easier to use: i.e. for example the XDocument
and XElement
classes.

- 54,973
- 13
- 116
- 224
-
-
I haven't used other stuff like XPathNavigator; feel free to edit my answer if you want to include/mention it. – ChrisW Jan 14 '09 at 18:49
By far the simplest method I've found for dealing with XML in C# is to use the XML Serialization tools. For example: http://www.dotnetjohn.com/articles.aspx?articleid=173.
Essentially, you can define C# classes that match your XML file (in fact, you can have them created for you if you have an XML definition file) and then you simply initialize instances of those classes directly from the XML file. Once you have them as instances, you can manipulate them as you wish and rewrite them back into XML files just as easily.

- 1,758
- 10
- 25
-
1Note for anyone visiting that link, it's currently got a redirect trojanin place as of 2018-04-16 – Patrick Apr 16 '18 at 21:35
In a performance critical application XmlReader/XmlWriter are a good choice (see here) for the sake of simplicity which is offered by Linq to XML and XmlDocument.

- 1,023,142
- 271
- 3,287
- 2,928
I've found the MvpXml project very useful in past scenarios where performance is a consideration. There's a wealth of knowledge about good practice within their project pages: http://www.codeplex.com/MVPXML

- 432
- 2
- 8