Click here to Skip to main content
15,885,546 members
Articles / Desktop Programming / Windows Forms
Article

XML C# STARTING GUIDE First Part

Rate me:
Please Sign up or sign in to vote.
1.86/5 (9 votes)
3 Nov 20074 min read 27.6K   346   19   1
First Part of a Starting Guide for XML with C#, Methods to manipulate XML in C#

Introduction

I have worked on different software projects for web and desktop applications. In one of my assignments as consultant I had my first contact with XML but in ASP with XmlDom. Now I'm developing C# and reading a book to improve my XML skills I decided to publish this article as a simple guide to start with XML with C# with some samples that I learned with some corrections I did to the book. For obvious reasons I don't mention the name to the book to don't affect the name of the publisher. For someone could be too easy this work and I think so but when I write something is easier for me to understand and remember what I have learned.

Background

After the speech in the last paragraph I will go ahead to theme, that is How to manipulate XML in .NET with C#. In this Article (that I'm thinking as a first part of a serial about the topic if people like it) I will be working with a simple example but it is enough to show the different ways to manipulate XML in .NET. To do that we'll be using a sample xml file that will be constructed in one of the code snippets in this article later. If you try to test the code you should run the code at the end of this article that constructs the XML file. The simple sample I mentioned before is a windows application Form with a ListBox on it and button to execute the code. There is one project in the solution uploaded for each code explained here.

Using the code

Three ways to Work with XML

  • First the developers not ready to change to new technology or that need to stay working with something similar to SAX can do them with MSXML. The bad thing is that in order to do use that you need to add a reference to your project that is of COM then it is not managed code. As you may know you should go to Solution Explorer , select your project and select Add Reference then in the screen that opens go to COM tab and look for Microsoft XML , v4.0 ( this can work with v2.0, v3.0 and so on… in my computer I had v7.0).

    Once you did that go to your code an in the file you need to use it you should add

    using MSXML2;

    With that NameSpace you can use the class DOMDocument40 (depends on the version that selected)

    Then in MSXMLSample we can see the following lines in the code in the form

    C#
    private void button1_Click(object sender, EventArgs e)
    {
        doc = new DOMDocument40();
        doc.load(@"..\..\..\books.xml");
    
        IXMLDOMNodeList nodes;
        nodes = doc.selectNodes("bookstore/book/title");
        IXMLDOMNode node = nodes.nextNode();
    
        while (node != null)
        {
            listBox1.Items.Add(node.nodeTypedValue);
            node = nodes.nextNode();
        }
    }

    The second and third method to manipulate XML is using the namespace System.Xml having:

  • Second method using XmlReader. In this section I will explain how the XmlReader and XmlWriter works in .NET. They are abstract so the can't be instantiated but both have a method Create that helps you makes an object to use the methods implicit on them. Both classes are forward only and you are not able insert another nodes to the Xml structure once it is defined.

    Then the way to use XmlReader is

    XmlReader rdr = XmlReader.Create(@"..\..\..\books.xml");

    Same for XmlWriter

    XmlWriter rdr = XmlWriter.Create(@"..\..\..\books.xml");

    The last sample with this method is on XmlReaderSample project

    C#
    private void button1_Click(object sender, EventArgs e)
    {
        XmlReader rdr = XmlReader.Create(@"..\..\..\books.xml");
    
        while (rdr.Read())
        {
            if (rdr.NodeType == XmlNodeType.Element)
            {
                if (rdr.Name == "title")
                {
                    listbox1.Items.Add(rdr.ReadElementContentAsString());
                }
            }
        }
    }
  • Third method is using the class XmlDocument. Some differentces with second method classes is that this class should be instantiated, is not forward only and also you can insert nodes or values anywhere you want. It is more flexible than the others classes explained before.Is easier to manipulate the XML File and you donÝt need to have a loop to find the element you are looking for

    The sample with this method is on XmlDocumentSample project

    C#
    private void button1_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(@"..\..\..\books.xml");
    
        XmlNodeList nodes = doc.GetElementsByTagName("title");
        foreach (XmlNode node in nodes)
        {
            listBox1.Items.Add(node.InnerText);
        }
    }

Finally I'll put code to construct the XML file used the samples

That can be accomplished with XmlWriter and also with XmlDocument. For time reasons I will use XmlWriter. Also in this sample I will apply settings to the creation of my XML file using the XMLWriterSettings class that is useful to define properties as the indent method, the end of line, etc. The settings are applied in the method create to have a XmlWriter object.

The code is on XmlWriterSample project and we'll se the code statement by statement to explain the different methods to create the structure of the document.

First we have

writer.WriteStartDocument();

This line starts the document adding the xml declaration if you don't specify in the settings not to include it.

To start and Element in the XML Document

writer.WriteStartElement("bookstore");

The code complete is

C#
private void button1_Click(object sender, EventArgs e)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.NewLineChars = "\r\n";

    XmlWriter writer = XmlWriter.Create(@"..\..\..\books.xml",settings);
    writer.WriteStartDocument();
    writer.WriteStartElement("bookstore");
    writer.WriteStartElement("book");
    writer.WriteElementString("title", "Microsoft Visual C# 2005 Unleashed");
    writer.WriteElementString("title", "Professional C#, Third Edition");
    writer.WriteElementString("title", 
        "Professional UML with Visual Studio .NET");
    writer.WriteElementString("title", "Learning JavaScript");
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();

    writer.Flush();
    writer.Close();
}

Points of Interest

This is my first article about XML in C# if you like it I'm thinking make a second part including more about XML XSD Schema Validation and XPath and more interesting XML stuff.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Graduated from Technological Institute of Hermosillo (my city) as Computer Systems Engineer. I have worked with three companies where I developed some desktop and web aapplications. I love programmning, playing the violin and being with my family.

I´m married with a beatiful daughter.

Comments and Discussions

 
Generalfantastic Pin
Pola A. Edward12-Mar-09 14:54
Pola A. Edward12-Mar-09 14:54 

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.