Home

Operations on XML Elements

   

Fundamental Operations

 

Introduction

So far, to create an XML element, we were directly typing in a file. When such a file has been created and saved, it is ready to be processed. Here is an example of a file named Videos.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Videos>
	<Title>The Distinguished Gentleman</Title>
</Videos>

In some applications, you will want the user to provide you with the necessary value(s) to create an element. Fortunately, XmlDocument, the XmlNode, and the XmlElement classes provide all the necessary properties and methods to perform the routine operations of an XML file, an element, or a node. The operations include locating a node, adding a new element, or deleting a node.

Before performing an operation, you will usually need to decide in what section of the file you want to action to bee applied. As it happens, you have the root node, a particular node inside the file, parent of a node, the sibling of a node, etc. To get to a node, you will usually first get a reference to its XmlElement. To do this, you can declare an XmlElement variable and initialize it with that reference.

Practical LearningPractical Learning: Introducing operations on XML Elements

  1. Start Microsoft Visual C# and create a Console Application named CollegeParkAutoParts3
  2. On the main menu, click Project -> Add New Item...
  3. In the Templates list, click XML File
  4. Set the Name to makes and click Add
  5. Change the file as follows:
     
    <?xml version="1.0" encoding="utf-8"?>
    <Makes>
      <Make>Acura</Make>
      <Make>Audi</Make>
      <Make>BMW</Make>
      <Make>Chevrolet</Make>
    </Makes>
  6. On the main menu, click File -> Save makes.xml As...
  7. Access the main folder of the current project and, inside of it, open a sub-folder of the same name (it should be opened already). In the sub-folder of the same name, open the bin sub-folder followed by the Release sub-folder. Click Save
  8. In the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> New Item...
  9. In the Templates list, make sure XML File is selected.
    Set the Name to models and click Add
  10. To save the file, on the main menu, click File -> Save models.xml As...
  11. Access the main folder of the current project and, inside of it, open a sub-folder of the same name (it should be selected already). In the sub-folder of the same name, open the bin sub-folder followed by the Release sub-folder. Click Save
  12. Change the file as follows:
     
    <?xml version="1.0" encoding="utf-8" ?>
    <Models>
    	<Model>NSX</Model>
    	<Model>TL</Model>
    	<Model>Spider</Model>
    	<Model>A4</Model>
    	<Model>RS6</Model>
    	<Model>323I</Model>
    	<Model>M5</Model>
    	<Model>Astro</Model>
    	<Model>Cavalier</Model>
    	<Model>Prot&#233;g&#233;</Model>
    </Models>

Adding an Empty Element

To assist with programmatically creating a new element, the XmlDocument class provides the CreateElement() method that is overloaded with three versions. One of the versions uses the following syntax:

public XmlElement CreateElement(string name);

Using this method, to create a new element, call it and pass it the name of the element. For example, imagine you want to add a new Title element to the above file. You would start with code as follows:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmNew = xmlDoc.CreateElement("Title");
            }

            Console.WriteLine();
            return 0;
        }
    }
}

In order to add the new element to the file, you must specify its position in the tree: whether it would be the first or the last node, whether you want to position it before or after a node of your choice. For example, if you want to add a new Title element to the above file, it would be considered a child of the root, that is, a child of the XmlDocument.DocumentElement property. In the previous lesson, we learned how to get a reference to the root node.

To support the positions of existing nodes, the XmlNode class, which is the ancestor of all XML nodes of the .NET Framework, provides various appropriate methods. One of these methods is AppendChild(), which is used to add an element as the last child of its parent. The syntax of the XmlNode.AppendChild() method is:

public virtual XmlNode AppendChild(XmlNode newChild);

When calling this method, pass the XmlNode object you had previous created. After adding the node, if you want the file to keep it, you should save it. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlElement elmNew = xmlDoc.CreateElement("Title");
                elmRoot.AppendChild(elmNew);
                xmlDoc.Save(strFilename);
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Title>The Distinguished Gentleman</Title>
  <Title />
</Videos>

Notice that the newly added element is empty.

Adding an Element With Value

If you want the element to have a value, the XmlDocument class provides the CreateTextNode() method. This method returns an XmlText value. The syntax of this method is:

public virtual XmlText CreateTextNode(string text);

This method takes as argument the string that would constitute the value of the element. Before calling it, you should have used the XmlNode.AppendChild() method to create a node. Calling this method on the LastChild node of the one that called the AppendChild() would specify the value of the new node. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlElement elmNew = xmlDoc.CreateElement("Title");
                XmlText txtVideo = xmlDoc.CreateTextNode("Basic Instinct");
                elmRoot.AppendChild(elmNew);
                elmRoot.LastChild.AppendChild(txtVideo);

                xmlDoc.Save(strFilename);
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Title>The Distinguished Gentleman</Title>
  <Title />
  <Title>Basic Instinct</Title>
</Videos>

The combination of calls to XmlDocument.CreateElement() and XmlDocument.CreateTextNode() allow you to create a new element that has a value.

Consider the following file:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
    <Title>The Distinguished Gentleman</Title>
  </Video>
  <Video>
    <Title>Basic Instinct</Title>
  </Video>
</Videos>

Notice that the root, Videos, has a repetitive child named Video. This Video child has its own child named Title. Imagine that you want to add a new Video node that has a child. To do this, first create an empty Video node as a child of the root. We learned earlier how to do that:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlElement elmNew = xmlDoc.CreateElement("Video");
                elmRoot.AppendChild(elmNew);
            }

            Console.WriteLine();
            return 0;
        }
    }
}

After creating the new child of the root, initialize the grand child with the desired name (the name doesn't have to be one of the existing names) and a value (which is optional if you don't want the new node to have a value). Once the new node is ready, append it as the last child of the root. If this new node has a value, append its XmlText object as the LastChild of the LastChild of the root. Here is an example of how you would do this:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlElement elmNew = xmlDoc.CreateElement("Video");
                elmRoot.AppendChild(elmNew);

                elmRoot = xmlDoc.DocumentElement;

                elmNew = xmlDoc.CreateElement("Title");
                XmlText txtVideo = xmlDoc.CreateTextNode("Her Alibi");
               
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);
                
                xmlDoc.Save(strFilename);
            }

            Console.WriteLine();
            return 0;
        }
    }
}

With this code you would go from this:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
    <Title>The Distinguished Gentleman</Title>
  </Video>
  <Video>
    <Title>Basic Instinct</Title>
  </Video>
</Videos>

To this:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
    <Title>The Distinguished Gentleman</Title>
  </Video>
  <Video>
    <Title>Basic Instinct</Title>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
  </Video>
</Videos>

Now consider the following file:

<?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>
</Videos>

The root, Videos, has a child named Video. The Video node has many child nodes. By now, we know how to add a child to the root. We also saw how to add a grand child with value to the root. To had many (grand) children to a node, first build the node, add it to the root, then continuously add the necessary nodes, one at a time, including its name and its optional value. This would be done as follows:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlElement elmNew = xmlDoc.CreateElement("Video");
                elmRoot.AppendChild(elmNew);

                elmRoot = xmlDoc.DocumentElement;

                elmNew = xmlDoc.CreateElement("Title");
                XmlText txtVideo = xmlDoc.CreateTextNode("The Day After Tomorrow");
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);

                elmNew = xmlDoc.CreateElement("Director");
                txtVideo = xmlDoc.CreateTextNode("Roland Emmerich");
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);
                
                elmNew = xmlDoc.CreateElement("Length");
                txtVideo = xmlDoc.CreateTextNode("124 Minutes");
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);
                
                elmNew = xmlDoc.CreateElement("Format");
                txtVideo = xmlDoc.CreateTextNode("DVD");
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);
                
                elmNew = xmlDoc.CreateElement("Rating");
                txtVideo = xmlDoc.CreateTextNode("PG-13");
                elmRoot.LastChild.AppendChild(elmNew);
                elmRoot.LastChild.LastChild.AppendChild(txtVideo);

                xmlDoc.Save(strFilename);
            }

            Console.WriteLine();
            return 0;
        }
    }
}

 This would produce:

<?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>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

Using the same approach, you can add children to children of children, and so on.

Practical Learning Practical Learning: Programmatically Adding an Element

  1. To give the user the ability to create a new car make, change the Program.cs file as follows:
     
    using System;
    using System.Xml;
    
    namespace CollegeParkAutoParts3
    {
        public static class Program
        {
            public static void CreateNewMake()
            {
                string strNewMake = "";
    
                Console.Write("Enter Car Make: ");
                strNewMake = Console.ReadLine();
    
                // Open the Makes.xml file
                XmlDocument docXMLFile = new XmlDocument();
                docXMLFile.Load("Makes.xml");
    
                // Get the root node so we can explore its children
                XmlElement nodRoot = docXMLFile.DocumentElement;
                // Store all the values of the elements in a string
                string allMyChildren = nodRoot.InnerText;
                // Locate the new make among the values of the elements
                int indexLookForNewMake =
                    allMyChildren.IndexOf(strNewMake);
    
                // If the car make exists already, don't add it
                if (indexLookForNewMake >= 0)
                    return;
                else
                {
                    // If the car is not in the list
                    // already, add it as a Make element
                    XmlElement elmXML =
                        docXMLFile.CreateElement("Make");
                    // Create its value using the 
                    // string provided by the user
                    XmlText txtXML = 
                        docXMLFile.CreateTextNode(strNewMake);
                    // Add the new element at the end of the file
                    docXMLFile.DocumentElement.AppendChild(elmXML);
                    // Specify its text
                    docXMLFile.DocumentElement.LastChild.AppendChild(txtXML);
    
                    // Save the file
                    docXMLFile.Save("Makes.xml");
                }
            }
           
            static int Main(string[] args)
            {
                return 0;
            }
        }
    }
  2. To give the user the ability to add a new car model, create the following function in the file:
     
    using System;
    using System.Xml;
    
    namespace CollegeParkAutoParts2
    {
        public static class Program
        {
            public static void CreateNewMake()
            {
                . . . No Change
            }
    
            public static void CreateNewModel()
            {
                string strNewModel = "";
    
                Console.Write("Enter Car Model: ");
                strNewModel = Console.ReadLine();
    
                XmlDocument docXMLFile = new XmlDocument();
                docXMLFile.Load("models.xml");
    
                XmlElement nodRoot = docXMLFile.DocumentElement;
                string allMyChildren = nodRoot.InnerText;
                int indexNewModel =
                    allMyChildren.IndexOf(strNewModel);
    
                if (indexNewModel >= 0)
                    return;
                else
                {
                    XmlElement elmXML =
                        docXMLFile.CreateElement("Model");
                    XmlText txtXML =
                        docXMLFile.CreateTextNode(strNewModel);
    
                    docXMLFile.DocumentElement.AppendChild(elmXML);
                    docXMLFile.DocumentElement.LastChild.AppendChild(txtXML);
    
                    docXMLFile.Save("models.xml");
                }
            }
    
            static int Main(string[] args)
            {
                return 0;
            }
        }
    }
  3. To guide the user with a menu, change the file as follows:
     
    using System;
    using System.Xml;
    
    namespace CollegeParkAutoParts2
    {
        public static class Program
        {
            public static void CreateNewMake()
            {
                . . . No Change
            }
    
            public static void CreateNewModel()
            {
                . . . No Change
            }
    
            static int Main(string[] args)
            {
                char mnuChoice = 'q';
    
                Console.WriteLine("=o=o=o=o=o=o=o=o=o=o=o=o=o=o=o=");
                Console.WriteLine("=-= College Park Auto-Parts =-=");
                Console.WriteLine("=o=o=o=o=o=o=o=o=o=o=o=o=o=o=o=");
    
                do
                {
                    try
                    {
                        Console.WriteLine("=-= Main Menu =-=");
                        Console.WriteLine("1 - Add New Car Make");
                        Console.WriteLine("2 - Add New Car Model");
                        Console.WriteLine("0 - Exit");
                        Console.Write("Your Choice: ");
                        mnuChoice = char.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Choice");
                        Console.WriteLine("Please try again");
                    }
    
                    switch (mnuChoice)
                    {
                        case '1':
                            CreateNewMake();
                            break;
                        case '2':
                            CreateNewModel();
                            break;
                        default:
                            break;
                    }
    
                    Console.WriteLine();
                } while((mnuChoice == '1') ||
                        (mnuChoice == '2'));
    
                Console.WriteLine("\nThank you!");
                return 0;
            }
        }
    }
  4. Execute the application and create the following elements:
     
    Makes
    Dodge
    Ford
    Honda
    Toyota
    Models
    A4 Quattro
    Corolla
    Dakota
    Focus
    Escort
    Camry
    Crown Victoria
    Expedition
    Integra
    Neon
  5. Close the DOS window

Adding a Filled Child Element

The above Videos.xml file had only one level under the root and no child element of the root had children. Suppose you have the following version of the file:

<?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>
</Videos>

Imagine that you want to add a Video element. You have a choice of adding one, more, or all child elements of the Video node. To perform this operation, one solution you can use is to "build" all child elements of the Video element, then add the node as a whole. To support this technique, we saw earlier that the XmlNode.InnerXml property comprises a node, its markup, its children and their markup. This means that you can create the child nodes with their markup(s) as a string and assign that string to an XmlNode.InnerXml string. To do this, you would need the set version of the InnerXml property. It is declared as follows:

public virtual string InnerXml{get; set;}

Here is an example that adds a complete new Video node to the above XML file:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                XmlElement elmXML = xmlDoc.CreateElement("Video");
                string strNewVideo = "<Title>Other People's Money</Title>" +
                                     "<Director>Alan Brunstein</Director>" +
                                     "<Length>114 Minutes</Length>" +
                             	     "<Format>VHS</Format>" +
                             	     "<Rating>PG-13</Rating>";

                elmXML.InnerXml = strNewVideo;
                xmlDoc.DocumentElement.AppendChild(elmXML);

                xmlDoc.Save("Videos.xml");
            }

            Console.WriteLine();
            return 0;
        }
    }
}

Inserting an Element

 

Locating an Element

So far, we have been adding nodes quite randomly, that is, without much precision. In some cases, you may want to perform an operation on an existing and particular node. For example, you may want to change the value of a node, you may want to add a new child node to an existing node, etc. Before taking any of these actions, you must be able to locate or identify the desired element.

To assist you with finding a node, the XmlDocument class is equipped with the GetElementByTagName() method which is overloaded with two versions. One of the syntaxes used is:

public virtual XmlNodeList GetElementsByTagName(string name);

This method takes as argument a string. The string must be the Name of a node. If at least one node that holds that name exists in the file, this method returns a collection of the nodes with that name. If there is no node with that name, the collection is returned empty and there is no exception.

Here is an example of calling the method:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of nodes whose name is Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // Now you can check each node of the list
                foreach(XmlNode node in lstTitles)
                {
                    ;
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

Once you have a list of the nodes of a particular criterion, you can then act as you see fit. For example, For example, you can look for a particular node that holds a text of your choice. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;
                //XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");

                // Create a list of nodes whose name is Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // Now you can check each node of the list
                foreach(XmlNode node in lstTitles)
                {
                    if (node.InnerText == "Her Alibi")
                    {
                        ;
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

Inserting an Element as a Last Child

Once again, consider our Videos.xml file:

<?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>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

Imagine you want to add a list of actors of the Her Alibi video. The first action to take is to locate the video, which you can do by calling the XmlDocument.GetElementsByTagName() method applied to a collection of nodes whose names are Video. From this list of nodes, you can look for the node whose value is "Her Alibi". Once you have found this element, get a reference to its parent. Then add the new node as the LastChild object of its parent. This can be done as follows:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of nodes whose name is Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // visit each node named Title
                foreach(XmlNode node in lstTitles)
                {
                    // When you get to a node, look for the element's value
                    // If you find an element whose value is Her Alibi
                    if (node.InnerText == "Her Alibi")
                    {
                        // Create an element named Actors
                        XmlElement elmNew = xmlDoc.CreateElement("Actors");
                        XmlNode elmParent = node.ParentNode;
                        // Add a new element named Actors to it
                        elmParent.AppendChild(elmNew);
                        xmlDoc.Save(strFilename);
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?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>
    <Actors />
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

This code creates an empty element. If you want to create an element that includes a value, create its text and add that text as the LastChild of its parent. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of nodes whose name is Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // visit each node named Title
                foreach(XmlNode node in lstTitles)
                {
                    // When you get to a node, look for the element's value
                    // If you find an element whose value is Her Alibi
                    if (node.InnerText == "The Distinguished Gentleman")
                    {
                        // Create an element named Category
                        XmlElement elmNew = xmlDoc.CreateElement("Category");
                        // Create the text of the new element
                        XmlText txtCatetory = xmlDoc.CreateTextNode("Comedy");
                        // Get a reference to the parent of the node we have found
                        XmlNode elmParent = node.ParentNode;
                        // Add the new element to the node we found
                        elmParent.AppendChild(elmNew);
                        // Specify the text of the new node
                        elmParent.LastChild.AppendChild(txtCatetory);
                        // Save the file
                        xmlDoc.Save(strFilename);
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?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>
    <Category>Comedy</Category>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

Using the same approach combined with what we learned about adding an item, you can add a new element that itself has child nodes. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of nodes whose name is Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // visit each node named Title
                foreach(XmlNode node in lstTitles)
                {
                    // When you get to a node, look for the element's value
                    // If you find an element whose value is The Day After Tomorrow
                    if (node.InnerText == "The Day After Tomorrow")
                    {
                        // Create an element named Actors
                        XmlElement elmNew = xmlDoc.CreateElement("Actors");
                        // Get a reference to the parent of the node we have found
                        XmlNode elmVideo = node.ParentNode;
                        // Add the new element to the node we found
                        elmVideo.AppendChild(elmNew);

                        // Create an element as a child of the new element
                        // Specify its name as Actor
                        elmNew = xmlDoc.CreateElement("Actor");
                        // Create the text of the new element
                        XmlText txtActor = xmlDoc.CreateTextNode("Dennis Quaid");
                        // Add the new Actor element to the Actors node
                        elmVideo.LastChild.AppendChild(elmNew);
                        // Specify the text of the new node
                        elmVideo.LastChild.LastChild.AppendChild(txtActor);

                        // In the same way, add the other Actor nodes
                        elmNew = xmlDoc.CreateElement("Actor");
                        txtActor = xmlDoc.CreateTextNode("Jake Gyllenhaal");
                        elmVideo.LastChild.AppendChild(elmNew);
                        elmVideo.LastChild.LastChild.AppendChild(txtActor);
                        
                        elmNew = xmlDoc.CreateElement("Actor");
                        txtActor = xmlDoc.CreateTextNode("Emmy Rossum");
                        elmVideo.LastChild.AppendChild(elmNew);
                        elmVideo.LastChild.LastChild.AppendChild(txtActor);

                        elmNew = xmlDoc.CreateElement("Actor");
                        txtActor = xmlDoc.CreateTextNode("Dash Mihok");
                        elmVideo.LastChild.AppendChild(elmNew);
                        elmVideo.LastChild.LastChild.AppendChild(txtActor);
                        
                        // Save the file
                        xmlDoc.Save(strFilename);
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?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>
    <Category>Comedy</Category>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
    <Actors />
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
    <Actors>
      <Actor>Dennis Quaid</Actor>
      <Actor>Jake Gyllenhaal</Actor>
      <Actor>Emmy Rossum</Actor>
      <Actor>Dash Mihok</Actor>
    </Actors>
  </Video>
</Videos>

You can also insert one or more elements as children of an existing node after locating that node. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of nodes whose names are Title
                XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");

                // visit each node named Title
                foreach(XmlNode node in lstTitles)
                {
                    // When you get to a node, look for the element's value
                    // If you find an element whose value is Her Alibi
                    if (node.InnerText == "Her Alibi")
                    {
                        // Get a reference to the video node that is 
                        // the parent of the video titled Her Alibi
                        XmlNode elmVideo = node.ParentNode;

                        // Create a list of the child nodes of the Her alibi video
                        XmlNodeList lstActors = elmVideo.ChildNodes;

                        // Visit each item of the collection
                        // looking for an element named Actors
                        foreach (XmlNode nodActor in lstActors)
                        {
                            // If you find an element named Actors
                            if (nodActor.Name == "Actors")
                            {
                                // Create a new element named Actor
                                // Specify its name as Actor
                                XmlElement elmNew = xmlDoc.CreateElement("Actor");
                                // Create the text of the new element
                                XmlText txtActor = xmlDoc.CreateTextNode("Tom Selleck");
                                // Add the new Actor element to the Actors node
                                elmVideo.LastChild.AppendChild(elmNew);
                                // Specify the text of the new node
                                elmVideo.LastChild.LastChild.AppendChild(txtActor);

                                // Add other Actor nodes
                                elmNew = xmlDoc.CreateElement("Actor");
                                txtActor = xmlDoc.CreateTextNode("Paulina Porizkova");
                                elmVideo.LastChild.AppendChild(elmNew);
                                elmVideo.LastChild.LastChild.AppendChild(txtActor);

                                elmNew = xmlDoc.CreateElement("Actor");
                                txtActor = xmlDoc.CreateTextNode("William Daniels");
                                elmVideo.LastChild.AppendChild(elmNew);
                                elmVideo.LastChild.LastChild.AppendChild(txtActor);

                                // Save the file
                                xmlDoc.Save(strFilename);

				// Stop, in this example, we don't expect another Actors node
                                break;
                            }
                        }
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?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>
    <Category>Comedy</Category>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
    <Actors>
      <Actor>Tom Selleck</Actor>
      <Actor>Paulina Porizkova</Actor>
      <Actor>William Daniels</Actor>
    </Actors>
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
    <Actors>
      <Actor>Dennis Quaid</Actor>
      <Actor>Jake Gyllenhaal</Actor>
      <Actor>Emmy Rossum</Actor>
      <Actor>Dash Mihok</Actor>
    </Actors>
  </Video>
</Videos>
 

Practical Learning Practical Learning: Adding Elements

  1. In the Solution Explorer, right-click CollegeParkAutoParts3 -> Add -> New Item...
  2. In the Templates list, make sure XML File is selected.
    Set the Name to parts and click Add
  3. Change the file as follows:
     
    <?xml version="1.0" encoding="utf-8" ?>
    <Parts>
    	<Part>
    		<PartNumber>293749</PartNumber>
    		<Make>Acura</Make>
    		<Model>MDX 3.5 4WD</Model>
    		<CarYear>2005</CarYear>
    		<PartName>Air Filter</PartName>
    		<UnitPrice>16.85</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>283759</PartNumber>
    		<Make>Audi</Make>
    		<Model>A4 Quattro</Model>
    		<CarYear>2002</CarYear>
    		<PartName>Clutch Release Bearing</PartName>
    		<UnitPrice>55.50</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>491759</PartNumber>
    		<Make>Dodge</Make>
    		<Model>Neon</Model>
    		<CarYear>1998</CarYear>
    		<PartName>Crankshaft Position Sensor</PartName>
    		<UnitPrice>22.85</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>844509</PartNumber>
    		<Make>Chevrolet</Make>
    		<Model>Camaro</Model>
    		<CarYear>2000</CarYear>
    		<PartName>Control Module Connector</PartName>
    		<UnitPrice>25.65</UnitPrice>
    	</Part>
    </Parts>
  4. To save the file, on the main menu, click File -> Save parts.xml As...
  5. Access the main folder of the current project and, inside of it, open a sub-folder of the same name (you should be in that folder already). In the sub-folder of the same name, open the bin sub-folder followed by the Release sub-folder. Click Save
  6. To allow the user to create new parts, change the Program.cs file as follows:
     
    using System;
    using System.Xml;
    
    namespace CollegeParkAutoParts3
    {
        public static class Program
        {
            public static void CreateNewMake()
            {
                . . . No Change
            }
    
            public static void CreateNewModel()
            {
                . . . No Change
            }
    
            public static void AddNewPart()
            {
                int carYear;
                string strMake, strModel,
                       strPartNumber, strPartName;
                double unitPrice;
    
                // - Generate a random number between 100000 and 999999 - //
    
                // We will generate a random number for the item
                // To start, we will use the miliseconds as a seed
                int ms = DateTime.Now.Millisecond;
                Random rndNumber = new Random(ms);
                int next = rndNumber.Next(100000, 999999);
                // Display the new number in the Part # text box
                strPartNumber = next.ToString();
    
                //// - Let the user specify the car model year - ////
                int curYear = DateTime.Now.Year + 1;
    
                Console.WriteLine("Enter the following information " +
                                  "as is related to the new car part");
                Console.WriteLine("For the car model that the " +
                                  "new part is made for, enter the year");
                Console.Write("between 1960 and " + curYear + ": ");
                carYear = int.Parse(Console.ReadLine());
    
                // - Display the list of Makes to the user to select one - //
                // We will need a reference to the XML document
                XmlDocument docXML = new XmlDocument();
    
                // Open the Makes.xml file
                docXML.Load("Makes.xml");
    
                // Get a reference to the root node
                XmlElement nodRoot = docXML.DocumentElement;
                // Locate all nodes whose name is Make
                XmlNodeList nodItems =
                    nodRoot.GetElementsByTagName("Make");
                // Retrieve the value of each Make node and display
                // that value to the user
                Console.WriteLine("Here is a list of the car " +
                                  "makes in our system");
                for (int i = 0; i < nodItems.Count; i++)
                    Console.WriteLine(nodItems[i].InnerXml);
                Console.Write("From this list, enter the car " +
                              "make of the new part: ");
                strMake = Console.ReadLine();
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
                // - Display the list of car Models to the 
                // user to select one - //
                // Open the Models.xml file
                docXML.Load("Models.xml");
    
                // Get a reference to the root node
                nodRoot = docXML.DocumentElement;
                // Locate all nodes whose name is Model
                nodItems = nodRoot.GetElementsByTagName("Model");
                // Retrieve the value of each Model node and display
                // that value to the user
                Console.WriteLine("Here is a list of the " +
                                  "car models in our system");
                for (int i = 0; i < nodItems.Count; i++)
                    Console.WriteLine(nodItems[i].InnerXml);
                Console.Write("From this list, enter the car " +
                              "model of the part: ");
                strModel = Console.ReadLine();
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
                //// - Request the part name - ////
                Console.Write("Enter Part Name:  ");
                strPartName = Console.ReadLine();
    
                //// - Request the unit price - ////
                Console.Write("Enter Unit Price: ");
                unitPrice = double.Parse(Console.ReadLine());
    
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                Console.WriteLine("New Car Part Summary");
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                Console.WriteLine("Part #:     " + strPartNumber);
                Console.WriteLine("Model Year: " + carYear);
                Console.WriteLine("Car Make:   " + strMake);
                Console.WriteLine("Car Model:  " + strModel);
                Console.WriteLine("Part Name:  " + strPartName);
                Console.WriteLine("Unit Price: " + unitPrice);
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
                // XmlDocument docXML = new XmlDocument();
                docXML.Load("Parts.xml");
    
                XmlElement elmXML = docXML.CreateElement("Part");
                string strNewPart = "<PartNumber>" + strPartNumber +
                                    "</PartNumber>" +
                                    "<CarYear>" + carYear.ToString() +
                                    "</CarYear>" +
                                    "<Make>" + strMake + "</Make>" +
                                    "<Model>" + strModel + "</Model>" +
                                    "<PartName>" + strPartName +
                                    "</PartName>" + "<UnitPrice>" +
                                    unitPrice.ToString() + "</UnitPrice>";
    
                elmXML.InnerXml = strNewPart;
                docXML.DocumentElement.AppendChild(elmXML);
    
                docXML.Save("Parts.xml");
            }
    
            static int Main(string[] args)
            {
                char mnuChoice = 'q';
    
                Console.WriteLine("=o=o=o=o=o=o=o=o=o=o=o=o=o=o=o=");
                Console.WriteLine("=-= College Park Auto-Parts =-=");
                Console.WriteLine("=o=o=o=o=o=o=o=o=o=o=o=o=o=o=o=");
    
                do
                {
                    try
                    {
                        Console.WriteLine("=-= Main Menu =-=");
                        Console.WriteLine("1 - Add New Car Make");
                        Console.WriteLine("2 - Add New Car Model");
                        Console.WriteLine("3 - Add New Part");
                        Console.WriteLine("0 - Exit");
                        Console.Write("Your Choice: ");
                        mnuChoice = char.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Choice");
                        Console.WriteLine("Please try again");
                    }
    
                    switch (mnuChoice)
                    {
                        case '1':
                            CreateNewMake();
                            break;
                        case '2':
                            CreateNewModel();
                            break;
                        case '3':
                            AddNewPart();
                            break;
                        default:
                            break;
                    }
    
                    Console.WriteLine();
                } while((mnuChoice == '1') ||
                        (mnuChoice == '2') ||
                        (mnuChoice == '3') );
    
                Console.WriteLine("\nThank you!");
                return 0;
            }
        }
    }
  7. Execute the application and create the following parts:
     
    Year Make Model Part Name Unit Price
    1986 Acura Integra Alternator 110.75
    1996 Dodge Neon Brake Pads 34.95
    1996 Honda Civic Passenger Mirror 24.65
    2002 Audi A4 Quattro Exhaust Gasket 1.55
    1998 Honda Civic Brake Pads 34.85
    2004 Dodge Neon Radiator Fan Assembly 125.95
    2002 Audi A4 Quattro Axle Differential Bearing - Left 10.25
    2000 Ford Escort Crankshaft Position Sensor 18.65
    1998 Toyota Corolla Radiator 95.95
    2004 Dodge Neon Oil Pump 112.85
    2004 Honda Civic Oxygen Sensor 90.55
    2000 Ford Escort Right Caliper Assembly Front 32.85
    2004 Dodge Neon Exhaust Valve 5.85
    2002 Audi A4 Quattro Alternator 305.50
    1986 Acura Integra Fuel Cap (Regular) 4.15
    2004 Dodge Neon Clutch Release Bearing 25.75
    2002 Dodge Dakota Starter Motor 145.95
    2002 Acura NSX Oil Filter 7.05
    1998 BMW 325I Rack and Pinion Bellow Kit 19.25
    2001 Acura Integra Voltage Regulator 215.75
    2002 Audi A4 Quattro Muffler Hanger 3.35
    2002 Acura NSX Oil Drain Plug 1.35
    2002 Dodge Dakota Circuit Breaker 3.25
    2004 Dodge Neon Brake Pad 20.55
    2004 Honda Civic Fusible Link 3.35
    2002 Dodge Dakota Circuit Breaker 3.45
    2004 Honda Civic Differential Bearing 36.75
    1998 Toyota Corolla Thermostat Standard Temperature 9.35
    2002 Audi A4 Quattro Cooling Fan Sensor 8.65
    2002 Acura NSX Oil Pump Seal 12.55
    2004 Dodge Neon Master Cylinder w/o ABS w/2 Wheel 102.95
    2002 Acura NSX Valve Stem Oil Seal 1.75
    2002 Dodge Dakota Fuse 0.40
    1998 Toyota Corolla Regular Thermostat 11.15
  8. Close the DOS window

Insertion an Element Referencing a Sibling

Instead of simply adding a new node at the end of child nodes, you can specify any other position you want. For example, you may want the new node to precede an existing child node. To support this operation, the XmlNode class provides the InsertBefore() method. Its syntax is:

public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild);

The first argument of this method is the new node that will be added. The second argument is the sibling that will succeed the new node. Consider the following version of our Videos.xml file:

<?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>
    <Category>Comedy</Category>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
  <Video>
    <Title>Fatal Attraction</Title>
    <Director>Adrian Lyne</Director>
    <Length>119 Minutes</Length>
    <Format>DVD</Format>
    <Rating>R</Rating>
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

Imagine you want to create a new Category element below the Director element whose name is Adrian Lyne. You can first get a list of videos. Inside of each video, check the nodes and find out whether the video has a Director node whose text is Adrian Lyne. Once you find that node, you can add the new element after it. Here is an example:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of the videos
                XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");

                // visit each video
                foreach (XmlNode node in lstVideos)
                {
                    // Within a video, create a list of its children
                    XmlNodeList lstChildren = node.ChildNodes;

                    // Visit each child node
                    foreach (XmlNode dir in lstChildren)
                    {
                        // If the child node is (a director and its name is) Adrian Lyne
                        if (dir.InnerText == "Adrian Lyne")
                        {
                            // Create an element named Category
                            XmlElement elmNew = xmlDoc.CreateElement("Category");
                            // Specify the text of the new element
                            elmNew.InnerText = "Drama";
                            
                            // Insert the new node below the Adrian Lyne node Director
                            node.InsertAfter(elmNew, dir);

                            // Save the file
                            xmlDoc.Save(strFilename);

                            // Stop
                            break;
                        }
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

This would produce:

<?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>
    <Category>Comedy</Category>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
  <Video>
    <Title>Fatal Attraction</Title>
    <Director>Adrian Lyne</Director>
    <Category>Drama</Category>
    <Length>119 Minutes</Length>
    <Format>DVD</Format>
    <Rating>R</Rating>
  </Video>
  <Video>
    <Title>The Day After Tomorrow</Title>
    <Director>Roland Emmerich</Director>
    <Length>124 Minutes</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

In the same way, you can insert a new node after a child of a child (of a child of a child of a child) of any node.

If you want to new node to be positioned after an existing child node, you can call the XmlNode.InsertAfter() method. Its syntax is:

public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild);
 

Node Removal

If you have a node you don't want or don't need anymore in the file, you can delete it. To delete a node, the XmlNode class provides the RemoveChild() method. Its syntax is:

public virtual XmlNode RemoveChild(XmlNode oldChild);

This method takes as argument the node to delete. If the node exists, it would be deleted and the method would return it. If the node doesn't exist, nothing would happen. To effectively use this method, you should first locate the particular node you want to delete. You can look for it using any of the logics we have applied so far. Once you find the node, you can then delete it. Imagine you want to delete a node whose name is Director and whose value is Bruce Beresford. Here is an example of calling this method to perform the operation:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);

                // Get a reference to the root node
                XmlElement elmRoot = xmlDoc.DocumentElement;

                // Create a list of the videos
                XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");

                // visit each video
                foreach (XmlNode node in lstVideos)
                {
                    // Within a video, create a list of its children
                    XmlNodeList lstChildren = node.ChildNodes;

                    // Visit each child node
                    foreach (XmlNode dir in lstChildren)
                    {
                        // If the child node is Bruce Beresford
                        if (dir.InnerText == "Bruce Beresford")
                        {
                            node.RemoveChild(dir);
     
                            // Save the file
                            xmlDoc.Save(strFilename);

                            // Stop
                            break;
                        }
                    }
                }
            }

            Console.WriteLine();
            return 0;
        }
    }
}

To delete all child nodes of a node, you can call the XmlNode.RemoveAll() method. Its syntax is:

public virtual void RemoveAll();

When called, this method will remove all child nodes, if any, of their parent node.

 

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next