Working with XML in C#


XML in .NET

XML stands for eXtended Markup Language. XML is a very widely used format for exchanging data because it is a structured language which can be easily read by both humans and machines. Because it is a widely used format almost all the programming frameworks like Java, .NET, etc. provide build in classes to create, traverse and manipulate XML documents.

In this article we will introduce XML API’s provided by .NET framework at a very high level.

There are two widely used API’s in .NET framework to work with XML data.

  1. XML DOM/XPATH API
  2. LINQ to XML API

XML DOM/XPATH API

XML DOM API related core classes are present in System.Xml.dll assembly. Using the contained namespaces and types you can manipulate XML data in memory and also work with existing XML documents. The programming model of System.Xml.dll is Microsoft’s implementation of W3C Document Object Model. In this model, XML document is created from bottom up. First XML document is created, then each individual elements are created and added to the document.

Some of the important classes in System.Xml namespace are listed below.

Class

Description

XmlDocument

Represents an XML document.

XmlElement

Represents an element in XML document.

XmlAttribute

Represents an attribute of XmlElement.

XmlNode

Represents a single node in the document.

XmlReader

A reader that provides fast, non-cached, forward only read access to XML data.

XmlWriter

A writer that provides fast, non-cached, forward only way to generate streams or files that contains XML data.

 

LINQ to XML API

LINQ to XML related core classes are present in System.Xml.Linq.dll. It contains all the related classes to create, modify, persist and traverse XML documents. LINQ to XML uses a functional approach to manipulating XML data and is very different from DOM model. It’s much more intuitive and easy to use compared to DOM model.

Some of the important classes in System.Xml.Linq namespace are listed below.

Class

Description

XDocument

Represents an XML document.

XElement

Represents an Element in XML document.

XAttribute

Represents an attribute of XmlElement.

XNode

Represent an abstract node in XML tree.

XComment

Represents XML comment.

XText

Represents XML Text node.