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, then XmlWriter
is your friend.
For an XDocument
example:
Console.WriteLine(
new XElement("Foo",
new XAttribute("Bar", "some & value"),
new XElement("Nested", "data")));
Or the same with XmlDocument
:
XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);
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 100MB xml file from csv, you might consider XmlWriter
; this is more primative (a write-once firehose), but very efficient (imagine a big loop here):
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
Finally, via XmlSerializer
:
[Serializable]
public class Foo
{
[XmlAttribute]
public string Bar { get; set; }
public string Nested { get; set; }
}
...
Foo foo = new Foo
{
Bar = "some & value",
Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);
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 implementing IXmlSerializable
, in which case you haven't gained much by using XmlSerializer
).