ProAnswers.org

why we would use XDocument over XMLDocument ?

when I try to search the difference or benefits of them I can’t find something useful, could you please tell me why you would use one over another ?

If you’re using .NET version 3.0 or lower, you have to use XmlDocument aka the classic DOM API. Likewise you’ll find there are some other APIs which will expect this.

If you get the choice, however, I would thoroughly recommend using XDocument aka LINQ to XML. It's much simpler to create documents and process them. For example, it's the difference between:



XmlDocument doc = new XmlDocument(); 
XmlElement root = doc.CreateElement("root"); 
root.SetAttribute("name", "value"); 
XmlElement child = doc.CreateElement("child"); 
child.InnerText = "text node"; 
root.AppendChild(child); 
doc.AppendChild(root); 
 



and



XDocument doc = new XDocument( 
    new XElement("root", 
                 new XAttribute("name", "value"), 
                 new XElement("child", "text node")));



Namespaces are pretty easy to work with in LINQ to XML, unlike any other XML API I've ever seen:



XNamespace ns = "http://somewhere.com"; 
XElement element = new XElement(ns + "elementName"); 
// etc