Introduction
Most of the time, we have to handle different XML files in our application and for that, XML documents are usually recursively manipulated and different elements are added, changed and removed. Whereas, .NET provides us an extremely efficient alternate mechanism to define XML Document Object Model (DOM) against any XML file. This helps in easy manipulation of XML file the way we handle different class instances.
Background
By definition, “XML Document Object Model (DOM) is an in-memory representation of XML document”. .NET provides an efficient XML serialization mechanism using which one can easily read and write any XML document. In this tip, we will leverage the .NET capabilities to define an XML DOM to manipulate an XML document. This approach is really handy and can be used in diverse scenarios.
Using the Code
Let’s define BookStore
XML, where we want to store different Books
along with its author
detail. For such scenario, you will probably define something like this:
<BookStore>
<Books>
<Book Name=".NET Programming" Author="ABC" />
<Book Name="C# Programming" Author="ABC" />
<Book Name="VB.NET Programming" Author="ABC" />
</Books>
</BookStore>
So, how can we define the XML DOM for the above example? So here’s the answer in two simple steps:
Step 1: Define XML Element Equivalent .NET Classes
The first step to define DOM for a given BookStore
example is to create .NET equivalent class for each of the XML elements – Book
, Books
and BookStore
.
XML Book Element Equivalent .NET Class
public class Book
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Author")]
public string Author { get; set; }
}
XmlAttribute
tags specifies that “Name
” and “Author
” should be saved as XML attribute instead of an element. You can even specify a different name to use in XML file for class fields.
XML Books Element Equivalent .NET Class
public class Books
{
[XmlElement("Book")]
public List<Book> Book { get; set; }
}
Books
class can hold collection of books. That is why List<Book>
is used for handling purposes and XmlElement
specifies that Book
should be saved as XML Element. Similarly, you can specify a different name to use in XML file for a specified element.
XML BookStore Element Equivalent .NET Class
public class BookStore
{
[XmlElement("Books")]
public Books Books { get; set; }
}
Finally, the BookStore
class handles the instance of Books
.
Step 2: Define Save and Load Method
Next step is to define reading and writing mechanism to load and save changes to any of the preexisting XML file of BookStore
. If there is no existing BookStore
XML file, you can even programmatically populate the BookStore
instance and save it to file.
Let’s modify the BookStore
class and add load
and save
methods to serialize object of BookStore
to file and deserialize object of BookStore
from file.
public static BookStore Load(string fileName)
{
using (var reader = new System.IO.StreamReader(fileName))
{
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(BookStore));
return serializer.Deserialize(reader) as BookStore;
}
}
public void Save(string fileName)
{
using (var writer = new System.IO.StreamWriter(fileName))
{
System.Xml.Serialization.XmlSerializer x =
new System.Xml.Serialization.XmlSerializer(this.GetType());
x.Serialize(writer, this);
writer.Flush();
}
}
That’s all you have to do, in order to create XML DOM to any of the XML files.
Sample Code
Now with XML DOM, you can easily manage your XML file as you work with your class instances. You can easily add, modify and remove book from collection.
Undermentioned is the same code on how to load an existing BookStore.xml and add a new book to it and save it back to file.
BookStore bookStore = BookStore.Load("BookStore.xml");
bookStore.Books.Book.Add(new Book() { Name = "Sample Book", Author = "Asad" });
bookStore.Save("BookStore.xml");
Similarly, you can easily remove any book and modify an existing one.
Points of Interest
It was always a problem to load different XML files and manipulate them as XML document. By defining simple XML DOM mechanism provided by .NET, one can easily manipluate XML document as simple class objects. This approach really makes it easily to handle XML elements similar to how we handle different class fields.