What difference xmldocument vs xmlwriter?

2

What is the difference between the two classes?

In what situation does each fit the best?

    
asked by anonymous 14.03.2014 / 20:03

2 answers

6

XmlDocument represents an entire XML loaded into memory, whereas XmlWriter is an object that assists in writing XML in a stream.

XmlDocument

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.

XDocument

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")
    ));

XmlWriter

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.

    
14.03.2014 / 20:06
0

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.

    
14.03.2014 / 20:08