How can I generate valid XML in C#?
C# – How to build XML in C#
cxml
Related Topic
- C# – How to create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office
- Xml – What characters do I need to escape in XML documents
- C# – How to generate random alphanumeric strings
- Python – How to parse XML and count instances of a particular node attribute
- C# – How to generate a random int number
- Xml – How to comment out a block of tags in XML
- Xml – What does in XML mean
- Php – How to parse and process HTML/XML in PHP
Best Answer
It depends on the scenario.
XmlSerializer
is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5,XDocument
, etc. are also very friendly. If the size is very large, thenXmlWriter
is your friend.For an
XDocument
example:Or the same with
XmlDocument
:If you are writing a large stream of data, then any of the DOM approaches (such as
XmlDocument
/XDocument
, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from CSV, you might considerXmlWriter
; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):Finally, via
XmlSerializer
:This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with
XmlSerializer
is that it doesn't like to serialize immutable types : everything must have a public getter and setter (unless you do it all yourself by implementingIXmlSerializable
, in which case you haven't gained much by usingXmlSerializer
).