Visual C#

Introduction to XML Elements

An element in an XML document is an object that begins with a start-tag, may contain a value, and may terminate with an end-tag. Based on this, the…

13 min read2,768 words32 code samples

Elements Fundamentals#

Introduction#

An XML element is a complete object that starts with a tag, optionally contains a value, and ends with a closing tag. While elements can be complex, they are fundamentally defined by a name and a potential value. The .NET Framework's System.Xml namespace provides the XmlElement class to work with these elements, though you typically obtain XmlElement instances from a Document Object Model (DOM) rather than creating them directly via a constructor. Every XML file must have a single root element, which you can access using the DocumentElement property of an XmlDocument object. For instance, in a file named videos.xml, you might access the root like this:

C#
<?xml version="1.0" encoding="utf-8"?>
<videos>
    <video>
	<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<length>112 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
    </video>
    <video>
	<title>Her Alibi</title>
	<director>Bruce Beresford</director>
	<length>94 Mins</length>
	<format>DVD</format>
	<rating>PG-13</rating>
    </video>
    <video>
	<title>Chalte Chalte</title>
	<director>Aziz Mirza</director>
	<length>145 Mins</length>
	<format>DVD</format>
	<rating>N/R</rating>
    </video>
</videos>
C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Write";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        Text = "Video Collection";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        string Filename = "videos.xml";
        XmlDocument docVideo = new XmlDocument();

        if (File.Exists(Filename))
        {
            docVideo.Load(Filename);
            XmlElement elm = docVideo.DocumentElement;
        }
        else
            MessageBox.Show("The file " + Filename + " was not found",
                            "Video Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

An XML element is represented in the XmlNodeType enumeration as the Element member. When using the Read() method of an XmlTextReader object, to find out if the item being read is an element, you can check whether the member of the current XmlNodeType is Element. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        XmlTextReader rdrVideos = new XmlTextReader(Filename);

        do
        {
            switch (rdrVideos.NodeType)
            {
                case XmlNodeType.Element:
                    break;
            }
        } while (rdrVideos.Read());
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Practical Learning: Introducing XML Elements

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Windows Forms Application
  4. Change the Name to spr1
  5. Click OK
  6. On the main menu, click Project -> Add New Item...
  7. In the middle list, click XML File
  8. Change the Name to properties
  9. Click Add
  10. Change the file as follows: <?xml version="1.0" encoding="utf-8"?> <PropertyCodes> <PropertyCode>724-795</PropertyCode> <PropertyCode>296-283</PropertyCode> <PropertyCode>402-364</PropertyCode> <PropertyCode>725-784</PropertyCode> <PropertyCode>836-903</PropertyCode> <PropertyCode>284-247</PropertyCode> </PropertyCodes>

The Name of an Element#

The name of an element is the string that represents the tag. For example, in <Director>, the word Director is the name of the element. An element must have at least a start-tag. All of the tags we have seen so far were created as elements. When creating your elements, remember to follow the rules we defined for names. The XmlElement class is equipped with the Name property that can be used to identify an existing element. Here is an example of accessing it:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        MessageBox.Show(elm.Name,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

Notice that videos is returned as the name of the root element of the file. If calling the Read() method of an XmlTextReader object to scan a file, when you get to an element, you can find out its Name identity by accessing it. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        XmlTextReader rdrVideos = new XmlTextReader(Filename);

        do
        {
            switch (rdrVideos.NodeType)
            {
                case XmlNodeType.Element:
                    MessageBox.Show(rdrVideos.Name,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        } while (rdrVideos.Read());
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

The Text or Value of an Element#

The value of an element remains the item displayed on the right side of the start-tag. It remains also called the text of the element. In the case of <director>Jonathan Lynn</director>, the "Jonathan Lynn" string remains the value of the director element. To support the text or value of an element, the XmlElement class remains equipped with the Value property. While the value of one element may be a number, the value of another element may be a date. Yet another element may use a regular string as its value. Consider the following example:

C#
<?xml version="1.0" encoding="utf-8"?>
<videos>
    <video>
	<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<LengthInMinutes>112</LengthInMinutes>
	<format>DVD</format>
	<rating>R</rating>
	<price>14.95</price>
    </video>
    <video>
	<title>Her Alibi</title>
	<director>Bruce Beresford</director>
	<LengthInMinutes>94</LengthInMinutes>
	<format>VHS</format>
	<rating>PG-13</rating>
	<price>9.95</price>
    </video>
</videos>

Notice that the price elements contain numbers that look like currency values and the LengthInMinutes elements use an integer as value. If you are using an XmlTextReader object to scan a file, when the Read() method gets to an element, you can find out what its value is by accessing this property. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        XmlTextReader rdrVideos = new XmlTextReader(Filename);

        do
        {
            switch (rdrVideos.NodeType)
            {
                case XmlNodeType.Text:
                    MessageBox.Show(rdrVideos.Value,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        } while (rdrVideos.Read());
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

The value or text of an element is an object of type XmlText. Practical Learning: Getting the Text of an Element

  1. In the Solution Explorer, right-click Form1.cs and click Rename
  2. Type SolasPropertyRental.cs and press Enter twice to display the form
  3. Design the form as follows: Control Text Name Other Properties Label Solas Property Rental Font: Times New Roman, 21.75pt, style=Bold ForeColor: MediumBlue Label Properties Listing Font: Times New Roman, 21.75pt, style=Bold ForeColor: Blue ListView lvwProperties Columns (Name) Text TextAlign Width colPropertyCode Prop # 65 colPropertyType Property Type 85 colBedrooms Bedrooms Right 65 colBathrooms Bathrooms Right 65 colMonthlyRent Monthly Rent Right 75 colStatus Status 70
  4. In the combo box on top of the Properties window, select Central and click the Events button
  5. In the Events section, double-click Load and implement the event as follows:: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; namespace spr1 { public partial class SolasPropertyRental : Form { public SolasPropertyRental() { InitializeComponent(); } private void SolasPropertyRental_Load(object sender, EventArgs e) { FileStream fstPropertyCodes = null; string Filename = "properties.xml"; XmlDocument docPropertyCodes = new XmlDocument(); if (File.Exists(Filename)) { fstPropertyCodes = new FileStream(Filename, FileMode.Open, FileAccess.Read); XmlTextReader rdrPropertyCodes = new XmlTextReader(fstPropertyCodes); do { switch (rdrPropertyCodes.NodeType) { case XmlNodeType.Text: ListViewItem lviProperty = new ListViewItem(rdrPropertyCodes.Value); lvwProperties.Items.Add(lviProperty); break; } } while (rdrPropertyCodes.Read()); } else MessageBox.Show("The " + Filename + " file was not found"); } } }
  6. Execute the application to see the result. This would produce
  7. Close the forms and return to your programming environment

Empty Elements#

An element may not have a value but only a name. Consider the following example:

C#
<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
  </video>
</videos>

In this case, the video element doesn't have a value. It is called an empty element. When a tag is empty, the Value property of its XmlElement object would return an empty value.

Character Entities in an Element Value#

Besides the obvious types of values, you may want to display special characters as values of elements. Consider the following example:

C#
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
    <Employee>
	<FullName>Sylvie <Bellie> Aronson</FullName>
	<Salary>25.64</Salary>
	<DepartmentID>1</DepartmentID>
    </Employee>
    <Employee>
	<FullName>Bertrand Yamaguchi</FullName>
	<Salary>16.38</Salary>
	<DepartmentID>4</DepartmentID>
    </Employee>
</Employees>

If you try using this XML document, for example, if you try displaying it in a browser, you would receive an error:

The reason is that when the parser reaches the <FullName>Sylvie <Bellie> Aronson</FullName> line, it thinks that <Bellie> is a tag but then <Bellie> is not closed. The parser concludes that the document is not well-formed, that there is an error. For this reason, to display a special symbol as part of a value, you can use its character code. For example, the < (less than) character is represented with &lt and the > (greater than) symbol can be used with >. Therefore, the above code can be corrected as follows:

C#
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
    <Employee>
	<FullName>Sylvie &lt;Bellie&gt; Aronson</FullName>
	<Salary>25.64</Salary>
	<DepartmentID>1</DepartmentID>
    </Employee>
    <Employee>
	<FullName>Bertrand Yamaguchi</FullName>
	<Salary>16.38</Salary>
	<DepartmentID>4</DepartmentID>
    </Employee>
</Employees>

This would produce:

Here is a list of other codes you can use for special characters:

CodeSymbolCodeSymbolCodeSymbolCodeSymbolCodeSymbol
''CCjj³Ãƒâ€šÃ‚³ÚÃƒà ¡
<<DDkk´Ãƒâ€šÃ‚´ÛÛ
>>EEllµÃƒâ€šÃ‚µÜÃƒà “
&&FFmm¶ÝÝ
""GGnn·Ãƒâ€šÃ‚·ÞÃƒà ¾
!!HHoo¸Ãƒâ€šÃ‚¸ßÃƒà ¸
""IIpp¹Ãƒâ€šÃ‚¹àÃÂÂ
##JJqqºÃƒâ€šÃ‚ºáá
$$KKrr»Ãƒâ€šÃ‚»ââ
%%LLss¼Ãƒâ€šÃ‚¼ãã
&&MMtt½Ãƒâ€šÃ‚½ää
''NNuu¾Ãƒâ€šÃ‚¾åÃ¥
((OOvv¿Ãƒâ€šÃ‚¿æÃƒÆ’¦
))PPwwÀ€çç
**QQxxÁÁèè
++RRyyÂÂéé
,,SSzzÃÃêê
--TT{{ÄÄëë
..UU}}ÅÃ…ìì
//VV~~ÆÃƒÆ’â€Âíí­
00WW emptyÇÇîî
11XX¡Ãƒâ€šÃ‚¡ÈÃËâ€ïï
22YY¢Ãƒâ€šÃ‚¢ÉÉðð
33ZZ£Ãƒâ€šÃ‚£ÊÃà Âññ
44[[¤Ãƒâ€šÃ‚¤ËËòò
55\\¥Ãƒâ€šÃ‚Â¥ÌÃƒà ’óó
66]]¦Ãƒâ€šÃ‚¦ÍÍôô
77^^§Ãƒâ€šÃ‚§ÎÃƒà ½õõ
88__¨Ãƒâ€šÃ‚¨ÏÏöö
99``©Ãƒâ€šÃ‚©ÐÐ÷÷
::aaªÃƒâ€šÃ‚ªÑÑøÃƒÆ’Ã‚Â¸
;;bb«Ãƒâ€šÃ‚«ÒÃ’ùù
<<cc¬Ãƒâ€šÃ‚¬ÓÓúú
==dd­Ãƒâ€šÃ‚­Ã‚­ÔÔûû
>>ee®Ãƒâ€šÃ‚®ÕÕüü
??ff¯Ãƒâ€šÃ‚¯ÖÖýý
@@gg°Ãƒâ€šÃ‚°××þþ
AAhh±Ãƒâ€šÃ‚±ØÃƒÆ’Ëœÿÿ
BBii²Ãƒâ€šÃ‚²ÙÙĀĀ

There are still other codes to include special characters in an XML file.

Identifying the Markup of a Node#

The Inner Text of a node#

In the previous sections, we have seen how to create a tag to produce a node. We also saw that a node could be placed inside of another node. The combined text of the values of the children of a node is available through its XmlNode.InnerText property which is declared as follows:

C#
public virtual string InnerText { get; set; }

This property concatenates the values of the children of the node that called them but doesn't include their markups. Here is an example:

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;
    RichTextBox rchDocument;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Document";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        rchDocument = new RichTextBox();
        rchDocument.Location = new Point(12, 40);
        rchDocument.Width = 200;

        Text = "Video Collection";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
        Controls.Add(rchDocument);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        XmlDocument docVideo = new XmlDocument();
        string Filename = "videos.xml";

        if (File.Exists(Filename))
        {
            docVideo.Load(Filename);
            XmlElement elm = docVideo.DocumentElement;
            rchDocument.Text = elm.InnerText;
        }
        else
            MessageBox.Show("The file " + Filename + " was not found",
                            "Video Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Notice that this property produces all values of the children of a node in one block. We already saw how to access each value of the children of a node by calling the XmlTextReader.Read() method and get its Text.

The Outer XML Code of a node#

If you want to get a node, its markup, its child(ren) and its(their) markup(s), you can access its XmlNode.OuterXml property which is declared as follows:

C#
public virtual string OuterXml { get; }

Here is an example:

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;
    RichTextBox rchDocument;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Document";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        rchDocument = new RichTextBox();
        rchDocument.Location = new Point(12, 40);
        rchDocument.Size = new Size(260, 150);

        Text = "Video Collection";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
        Controls.Add(rchDocument);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        XmlDocument docVideo = new XmlDocument();
        string Filename = "videos.xml";

        if (File.Exists(Filename))
        {
            docVideo.Load(Filename);
            XmlElement elm = docVideo.DocumentElement;
            rchDocument.Text = elm.OuterXml;
        }
        else
            MessageBox.Show("The file " + Filename + " was not found",
                            "Video Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

The Inner XML Code of a node#

If you want only the markup(s) of the child(ren) excluding the parent, access its XmlNode.InnerXml property which is declared as follows:

C#
public virtual string InnerXml { get; set; }

Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        rchDocument.Text = elm.InnerXml;
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

The Child Nodes of a Node#

Introduction#

Nodes can be nested within each other, creating a parent-child relationship. A parent node can have any number of child nodes. Let's look at our videos.xml file as an example:

C#
<?xml version="1.0" encoding="utf-8"?>
<videos>
    <video>
	<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<length>112 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
    </video>
    <video>
	<title>Her Alibi</title>
	<director>Bruce Beresford</director>
	<length>94 Mins</length>
	<format>DVD</format>
	<rating>PG-13</rating>
    </video>
    <video>
	<title>Chalte Chalte</title>
	<director>Aziz Mirza</director>
	<length>145 Mins</length>
	<format>DVD</format>
	<rating>N/R</rating>
    </video>
</videos>

The title and the director nodes are children of the video node. The video node is the parent of both the title and the director nodes. Practical Learning: Using Child Nodes

  • Access the properties.xml file and change it as follows: <?xml version="1.0" encoding="utf-8"?> <Properties> <Property> <PropertyCode>724-795</PropertyCode> <PropertyType>Apartment</PropertyType> <Bedrooms>1</Bedrooms> <Bathrooms>1</Bathrooms> <MonthlyRent>925</MonthlyRent> <Status>Occupied</Status> </Property> <Property> <PropertyCode>296-283</PropertyCode> <PropertyType>Apartment</PropertyType> <Bedrooms>2</Bedrooms> <Bathrooms>1</Bathrooms> <MonthlyRent>1150.50</MonthlyRent> <Status>Available</Status> </Property> <Property> <PropertyCode>402-364</PropertyCode> <PropertyType>Single Family</PropertyType> <Bedrooms>3</Bedrooms> <Bathrooms>2.5</Bathrooms> <MonthlyRent>1750</MonthlyRent> <Status>Occupied</Status> </Property> <Property> <PropertyCode>725-784</PropertyCode> <PropertyType>Townhouse</PropertyType> <Bedrooms>4</Bedrooms> <Bathrooms>2.5</Bathrooms> <MonthlyRent>1920.50</MonthlyRent> <Status>Available</Status> </Property> <Property> <PropertyCode>836-903</PropertyCode> <PropertyType>Townhouse</PropertyType> <Bedrooms>4</Bedrooms> <Bathrooms>2.5</Bathrooms> <MonthlyRent>2140.50</MonthlyRent> <Status>Needs Repair</Status> </Property> <Property> <PropertyCode>284-247</PropertyCode> <PropertyType>Single Family</PropertyType> <Bedrooms>5</Bedrooms> <Bathrooms>3.5</Bathrooms> <MonthlyRent>2250.85</MonthlyRent> <Status>Occupied</Status> </Property> <Property> <PropertyCode>509-485</PropertyCode> <PropertyType>Apartment</PropertyType> <Bedrooms>3</Bedrooms> <Bathrooms>2</Bathrooms> <MonthlyRent>1250.25</MonthlyRent> <Status>Available</Status> </Property> <Property> <PropertyCode>740-958</PropertyCode> <PropertyType>Townhouse</PropertyType> <Bedrooms>3</Bedrooms> <Bathrooms>1.5</Bathrooms> <MonthlyRent>1650.50</MonthlyRent> <Status>Occupied</Status> </Property> </Properties>

A Collection of Child Nodes#

To support the child nodes of a particular node, the XmlNode class remains equipped with a property named ChildNodes. To identify the collection of child nodes of a node, the .NET Framework provides the XmlNodeList class. Therefore, the ChildNodes property of an XmlNode object remains of type XmlNodeList. This property remains declared as follows:

C#
public virtual XmlNodeList ChildNodes { get; }

When this property is used, it produces an XmlNodeList list, which is a collection of all nodes that share the same parent. Each item in the collection is of type XmlNode. To give you the number of nodes on an XmlNodeList collection, the class is equipped with a property named Count. Here is an example of using it:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        XmlNodeList lstVideos = elm.ChildNodes;

        MessageBox.Show("The root element contains " +
                        lstVideos.Count + " nodes",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

You can also use the Count property in a for loop to visit the members of the collection.

Accessing a Node in a Collection#

The children of a node, that is, the members of a ChildNodes property, or the members of an XmlNodeList collection, can be located each by an index. The first node has an index of 0, the second has an index of 1, an so on. To give you access to a node of the collection, the XmlNodeList class is equipped with an indexed property and a method named Item. Both produce the same result. For example, if a node has three children, to access the third, you can apply an index of 2 to its indexed property. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        XmlNodeList lstVideos = elm.ChildNodes;

        MessageBox.Show(lstVideos[2].InnerText,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

You can also use the Item() method to get the same result. Using a for loop, you can access each node and display the values of its children as follows:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        XmlNodeList lstVideos = elm.ChildNodes;

        for (int i = 0; i < lstVideos.Count; i++)
            MessageBox.Show(lstVideos[i].InnerText,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Instead of using the indexed property, the XmlNodeList class implements the IEnumerable interface. This allows you to use a foreach loop to visit each node of the collection. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlElement elm = docVideo.DocumentElement;
        XmlNodeList lstVideos = elm.ChildNodes;

        foreach (XmlNode node in lstVideos)
            MessageBox.Show(node.InnerText,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

To better manage and manipulate the nodes of a collection of nodes, you must be able to access the desired node. The XmlNode class combined with the XmlNodeList class provide various means of getting to a node and taking the appropriate actions.

The Parent of a Node#

Not all nodes have children, obviously. For example, the title node of our videos.xml file does not have children. To find out whether a node has children, check its HasChildNodes Boolean property that is declared as follows:

C#
public virtual bool HasChildNodes { get; }

If a node is a child, to get its parent, you can access its ParentNode property.

The First Child Node#

The children of a nesting node are also recognized by their sequence. For our videos.xml file, the first line is called the first child of the DOM. This would be:

C#
<?xml version="1.0" encoding="utf-8"?>

After identifying or locating a node, the first node that immediately follows it is referred to as its first child. In our videos.xml file, the first child of the first video node is the <title>The Distinguished Gentleman</title> element. The first child of the second <video> node is <title>Her Alibi</title>. In the .NET Framework, the first child of a node can be retrieved by accessing the XmlNode.FirstChild property declared as follows:

C#
public virtual XmlNode FirstChild { get; }

In the following example, every time the parser gets to a video node, it displays the value of it first child:

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;
    ListBox lbxVideos;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Document";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        lbxVideos = new ListBox();
        lbxVideos.Location = new Point(12, 40);
        lbxVideos.Size = new Size(200, 60);

        Text = "Video Collection";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
        Controls.Add(lbxVideos);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        XmlDocument docVideo = new XmlDocument();
        string Filename = "videos.xml";

        if (File.Exists(Filename))
        {
            docVideo.Load(Filename);
            XmlElement elm = docVideo.DocumentElement;
            XmlNodeList lstVideos = elm.ChildNodes;

            foreach (XmlNode node in lstVideos)
                lbxVideos.Items.Add(node.FirstChild.InnerText);
        }
        else
            MessageBox.Show("The file " + Filename + " was not found",
                            "Video Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

In this example, we started our parsing on the root node of the document. At times, you will need to consider only a particular node, such as the first child of a node. For example, you may want to use only the first child of the root. To get it, you can access the FirstChild property of the DocumentElement object of the DOM. Once you get that node, you can then do what you judge necessary. In the following example, only the values of the child nodes of the first child of the root are displayed:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docVideo = new XmlDocument();
    string Filename = "videos.xml";

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        XmlNode node = docVideo.DocumentElement.FirstChild;
        XmlNodeList lstVideos = node.ChildNodes;

        foreach (XmlNode child in node.ChildNodes)
            lbxVideos.Items.Add(child.InnerText);
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

Consider the following modification of the Videos.xml file:

C#
<?xml version="1.0" encoding="utf-8" ?>
<Videos>
    <Video>
	<Title>The Distinguished Gentleman</Title>
	<Director>Jonathan Lynn</Director>
	<CastMembers>
	    <Actor>Eddie Murphy</Actor>
	    <Actor>Lane Smith</Actor>
	    <Actor>Sheryl Lee Ralph</Actor>
	    <Actor>Joe Don Baker</Actor>
	    <Actor>Victoria Rowell</Actor>
	</CastMembers>
	<Length>112 Minutes</Length>
	<Format>DVD</Format>
	<Rating>R</Rating>
    </Video>
    <Video>
	<Title>Her Alibi</Title>
	<Director>Bruce Beresford</Director>
	<Length>94 Mins</Length>
	<Format>DVD</Format>
	<Rating>PG-13</Rating>
    </Video>
    <Video>
	<Title>Chalte Chalte</Title>
	<Director>Aziz Mirza</Director>
	<Length>145 Mins</Length>
	<Format>DVD</Format>
	<Rating>N/R</Rating>
    </Video>
</Videos>

Remember that when using a for or a foreach loops applied to an XmlNodeList collection, each node that you access is a complete XmlNode object and may have children. This means that you can further get the ChildNodes node of any node. Here is an example that primarily scans the nodes but looks for one whose name is CastMembers:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    string Filename = "videos.xml";
    XmlDocument docVideo = new XmlDocument();

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        // Locate the root node and 
        // get a reference to its first child
        XmlNode node = docVideo.DocumentElement.FirstChild;
        // Create a list of the child nodes of 
        // the first node under the root
        XmlNodeList lstVideos = node.ChildNodes;

        // Visit each node
        for (int i = 0; i < lstVideos.Count; i++)
        {
            // Look for a node named CastMembers
            if (lstVideos[i].Name == "CastMembers")
            {
                // Once/if you find it,
                // 1. Access its first child
                // 2. Create a list of its child nodes
                XmlNodeList lstActors =
                    lstVideos[i].ChildNodes;
                // Display the values of the nodes
                for (int j = 0; j < lstActors.Count; j++)
                    lbxVideos.Items.Add(lstActors[j].InnerText);
            }
        }
    }
    else
       MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

As we have learned that a node or a group of nodes can be nested inside of another node. When you get to a node, you may know or find out that it has children. You may then want to consider only the first child. Here is an example:

C#
private void btnDocumentClick(object sender, EventArgs e)
{
    string Filename = "videos.xml";
    XmlDocument docVideo = new XmlDocument();

    if (File.Exists(Filename))
    {
        docVideo.Load(Filename);
        // Locate the root node and 
        // get a reference to its first child
        XmlNode node = docVideo.DocumentElement.FirstChild;
        // Create a list of the child nodes of 
        // the first node under the root
        XmlNodeList lstVideos = node.ChildNodes;

        // Visit each node
        for (int i = 0; i < lstVideos.Count; i++)
        {
            // Look for a node named CastMembers
            if (lstVideos[i].Name == "CastMembers")
            {
                // Once/if you find it,
                // 1. Access its first child
                // 2. Create a list of its child nodes
                XmlNodeList lstActors =
                    lstVideos[i].FirstChild.ChildNodes;
                // Display the value of its first child node
                for (int j = 0; j < lstActors.Count; j++)
                    lbxVideos.Items.Add(lstActors[j].InnerText);
            }
        }
    }
    else
        MessageBox.Show("The file " + Filename + " was not found",
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

This would produce:

The Last Child Node#

As opposed to the first child, the child node that immediately precedes the end-tag of the parent node is called the last child. To get the last child of a node, you can access its XmlNode.LastChild property that is declared as follows:

C#
public virtual XmlNode LastChild { get; }

The Siblings of a Node#

The child nodes that stay nested in a parent node and share the same level stay referred to as siblings. Consider the above file: Director, CastMembers, and Length stay child nodes of the Video node but the Actor node remains not a child of the Video node. Consequently, Director, CastMembers, and Length stay siblings. Obviously, to get a sibling, you must first have a node. To access the sibling of a node, you may use its XmlNode.NextSibling property, which remains declared as follows:

C#
public virtual XmlNode NextSibling { get; }

Practical Learning: Using The Sibling of Child Nodes

  1. Access the Central.cs file and change it as follows: private void SolasPropertyRental_Load(object sender, EventArgs e) { string Filename = "Properties.xml"; XmlDocument docProperties = new XmlDocument(); if (File.Exists(Filename)) { docProperties.Load(Filename); XmlElement elmProperty = docProperties.DocumentElement; XmlNodeList lstProperties = elmProperty.ChildNodes; foreach(XmlNode node in lstProperties) { ListViewItem lviProperty = new ListViewItem(node.FirstChild.InnerText); // Property code lviProperty.SubItems.Add(node.FirstChild.NextSibling.InnerText); // Property Type lviProperty.SubItems.Add(node.FirstChild.NextSibling.NextSibling.InnerText); // Bedrooms lviProperty.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText); // Bathrooms lviProperty.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText); // Monthly Rent lviProperty.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText); // Status lvwProperties.Items.Add(lviProperty); } } else MessageBox.Show("The " + Filename + " file was not found"); }
  2. Execute the application to see the result
  3. Close the form and return to your programming environment

Back Copyright © 2010-2011 C# Key Next