Click here to Skip to main content
14,038,575 members
Click here to Skip to main content
Add your own
alternative version

Stats

15.4K views
17 bookmarked
Posted 3 Mar 2015
Licenced CPOL

Handle XML File Using XML DOM

, 3 Mar 2015
Rate this:
Please Sign up or sign in to vote.
This tip explains simple steps to define XML DOM against XML document. This way, you can easily manipulate XML document as simple class objects.

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Asad Bukhari
Software Developer (Senior)
Pakistan Pakistan
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
QuestionHow to I get the value (xmlelement?) Pin
George Sheehy4-Mar-15 9:13
professionalGeorge Sheehy4-Mar-15 9:13 
AnswerRe: How to I get the value (xmlelement?) Pin
Asad Bukhari4-Mar-15 18:34
memberAsad Bukhari4-Mar-15 18:34 
GeneralMy vote of 1 Pin
David Campen4-Mar-15 9:06
memberDavid Campen4-Mar-15 9:06 
GeneralRe: My vote of 1 Pin
Asad Bukhari4-Mar-15 18:47
memberAsad Bukhari4-Mar-15 18:47 
GeneralMy vote of 2 Pin
Jean-Pierre Bachmann4-Mar-15 2:37
professionalJean-Pierre Bachmann4-Mar-15 2:37 
GeneralRe: My vote of 2 Pin
Asad Bukhari4-Mar-15 18:50
memberAsad Bukhari4-Mar-15 18:50 
Bugsample is missing Pin
yixiaozi3-Mar-15 20:25
memberyixiaozi3-Mar-15 20:25 
GeneralRe: sample is missing Pin
Asad Bukhari4-Mar-15 18:39
memberAsad Bukhari4-Mar-15 18:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190425.1 | Last Updated 3 Mar 2015
Article Copyright 2015 by Asad Bukhari
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid