ProAnswers.org

Building XML using C# code?

Please indicate your best practices for building XML using C#.
What is the best way to build XML in C#?

1 Like

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 [b]large[/b] 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):