C#: XML with XDocuments
Comments available as RSS 2.0
I’ve always used XmlDocument when I’ve needed to create or read XML, but I while I was implmenting a SOAP service for ChickenPing I discovered XDocument. XDocument offers a much more concise way of specying XML without all the boilerplate code.
For example, this snippet using XmlDocument:
XmlElement root = doc.CreateElement("recipeml"); XmlElement hdVersion = doc.CreateElement("version"); hdVersion.InnerText = "0.5"; root.AppendChild(hdVersion); XmlElement hdGenerator = doc.CreateElement("generator"); hdGenerator.InnerText = "ChickenPing v" + Constants.GetVersion().ToString(3); root.AppendChild(hdGenerator); ...
Can be used to produce the same output as:
XElement root = new XElement("recipeml", new XElement("version", "0.5"), new XElement("generator", "ChickenPing v" + Constants.GetVersion().ToString(3))); ...
Fewer lines of code, and XDocument also supports methods to write to a file, a TextWriter, or an XmlWriter.

Comments
Leave a Comment