What is the difference between the two classes?
In what situation does each fit the best?
What is the difference between the two classes?
In what situation does each fit the best?
XmlDocument represents an entire XML loaded into memory, whereas XmlWriter is an object that assists in writing XML in a stream.
If you want to manipulate an XML, for example, load the same from a file, change some part of its structure and then save it, then I would use the XmlDocument for this. With it you can find the elements using XPath , which greatly facilitates manipulation.
This class and its related are part of .Net from version 3.5, much easier to work with than XmlDocument and related. If you want to create applications without taking the previous versions of .NET, then this is the recommended way.
To create a structure in Xml, you only need a declaration, instead of inserting nodes:
var xdocument = new XDocument(
new XElement("elementoRaiz",
new XAttribute("atributo1", "valor"),
new XElement("elementoFilho", "texto do elemento filho"),
new XElement("elementoFilho2", "texto do elemento filho 2")
));
If you just want to write an Xml to a file, for example, reading data from any source such as a database, you could use XmlWriter to write the XML as it reads the data from the database.
The XmlDocument is a more complex class than XmlWriter because it contains more methods for manipulating xml whereas XmlWriter basically serves to write that XML.