Fundamentals of Attributes

Introduction

When studying XML elements we saw how they constituted the main objects of an XML document. We also saw that an element could be nested inside of another element. Instead of nesting an element, you can transform the nested element into being part of the nesting element and thereby giving away its element qualities. This is the basis of an attribute.

An attribute is a value that is created as part of an element, making that value different from the value of a regular element. There are similarities and differences between an element and an attribute.

The element and the attribute have these in common:

The differences between an element and an attribute are:

The Structure of an Attribute

Imagine you have an ISBN element as a child of a Video element as follows:

<video>
	<ISBN>0-7888-1623-3</ISBN>
</video>

An attribute must be created inside the start-tag of an element. To manually create an attribute, type the left angle bracket of the element, followed by the name of the element, an empty space, and the name of the attribute. The name follows the same rules we defined for names in XML.

An attribute should have a value. To specify the value of an attribute, assign a string to its name. In the case of the above code fragment, since ISBN is simply a child of the video element, you can change the ISBN element to become an attribute of the video element as follows:

<video ISBN="0-7888-1623-3">

Now, ISBN is an attribute of the video element.

You will decide which elements of your XML document need attribute, the number and types of those attribute, etc. While a certain element may have an attribute, a sibling element with the same name and at the same level may not have an attribute or may have a completely different type of attribute. Here is an XML file with attributes in some elements:

<?xml version="1.0" encoding="utf-8" ?>
<videos>
    <video ISBN="0-7888-1623-3">
	<title Screenplay="Marty Kaplan">The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<length>112 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
    </video>
    <video>
	<title WrittenBy="Charlie Peter">Her Alibi</title>
	<director>Bruce Beresford</director>
	<length>94 Mins</length>
	<format>DVD</format>
	<rating>PG-13</rating>
    </video>
</videos>

When manually creating your attributes, to make your code easy to read, you can include white spaces between attributes. This means that you can type an attribute on the next line of its element's name. We know that we can close an element with an end-tag as follows:

<video><ISBN>0-7888-1623-3</ISBN></video>

We also saw that we could close an element locally as follows: <video />. If you create an attribute in an empty element, you can also close it by typing the indicative forward slash before the right angle bracket and after an empty space. Here is an example:

<video ISBN="0-7888-1623-3" />

Operations on an XML Attribute

Introduction

In the .NET Framework, an attribute is represented by a class named XmlAttribute:

public class XmlAttribute : System.Xml.XmlNode

The Name of an Attribute

Like all nodes, this class is derived from XmlNode. The name of an attribute is represented by a (read-only) property named Name:

public override string Name { get; }

The Value of an Attribute

The value of an attribute is represented by a property named Value:

public override string Value { get; set; }

The Contents of an Attribute

Besides Value, the XmlAttribute class is equipped with a write-only property named InnerText:

public override string InnerText { set; }

The XmlAttribute class is also equipped with a write-only property named InnerXml:

public override string InnerXml { set; }

Creating an Attribute

An element can have 0, one, or more attributes. To support the attributes of an element, the XmlElement class is equipped with a collection property named Attributes:

public override System.Xml.XmlAttributeCollection Attributes { get; }

The XmlElement.Attributes property is based on a sealed collection class named XmlAttributeCollection:

public sealed class XmlAttributeCollection : System.Xml.XmlNamedNodeMap, System.Collections.ICollection

As you can see, the XmlAttributeCollection class implements the ICollection interface.

Before performing an attribute-related operation on an element, to find out whether the element has any attribute, you can check the value of the Boolean HasAttributes property of its XmlElement element. If this property produces a true value, then the element has at least one attribute; otherwise, the element doesn't have any attribute.

Setting an Attribute on an Element

Consider an XML document as follows:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments>
	<store-item>
		<item-number>702481</item-number>
		<item-name>Vox Continental 73-key Performance Keyboard</item-name>
		<price>1925.45</price>
	</store-item>
	<store-item>
		<item-number>374857</item-number>
		<item-name>Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
		<price>194.25</price>
	</store-item>
	<store-item>
		<item-number>538580</item-number>
		<item-name>Mendini By Cecilio Kids Drum Set</item-name>
		<price>512.86</price>
	</store-item>
</musical-instruments>

As mentioned already, an attribute belongs to an element. This means that, when creating an attribute, you must specify the element wo which it will belong. To support the attributes of an element, the XmlElement class is equipped with a method named SetAttribute. This method is overloaded with two versions. One of the versions of this method uses the following syntax:

public virtual void SetAttribute(string name, string value);

The first argument is the name of the new attribute and the second argument will be its text. Before adding an attribute, you should first identify its parent element. Here is an example that adds an attribute to the root element:

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            XmlDocument xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Appliance Store\\StoreItems1.xml";

            xdStoreItems.Load(strStoreItems);

            // Create an attribute and add it to the root element
            xdStoreItems.DocumentElement!.SetAttribute("introduction", "Solo Music Store");

            xdStoreItems.Save(strStoreItems);
        }
    }
}

This would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
    <store-item>
        <item-number>702481</item-number>
        <item-name>Vox Continental 73-key Performance Keyboard</item-name>
        <price>1925.45</price>
    </store-item>
    <store-item>
        <item-number>374857</item-number>
        <item-name>Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
        <price>194.25</price>
    </store-item>
    <store-item>
        <item-number>538580</item-number>
        <item-name>Mendini By Cecilio Kids Drum Set</item-name>
        <price>512.86</price>
    </store-item>
</musical-instruments>

Adding an Attribute to an Element

To support attribute addition, the XmlDocument class is equipped with a method named CreateAttribute. It is overloaded in three versions. One of the versions of this method has the following syntax:

public XmlAttribute CreateAttribute(string name);

This method expects the name of the attribute as argument. If it succeeds, this method produces an XmlAttribute object. To add the new attribute to an element, you can call the XmlElement.SetAttributeNote() method. This method is overloaded in two versions. One of the versions uses the following syntax:

public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr);

This method expects an XmlAttribute object. Here is an example that looks for a particular video in a collection and adds an ISBN attribute to it:

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            // This is the DOM object of this project
            XmlDocument xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Solo Music Store\\StoreItems.xml";

            // Open the file and put the records in the DOM object
            xdStoreItems.Load(strStoreItems);

            // Create an attribute named "hand"
            XmlAttribute xaStoreItem = xdStoreItems.CreateAttribute("hand");
            // Set the value of the "hand" attribute to "left"
            xaStoreItem.Value = "left";

            /* Since we need to locate a particular node, 
             * we will check every item by its number. Therefore, 
             * get a list of all items by their items numbers. */
            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            // Visit each item
            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                // Look for a store item whose number is "374857"
                if (xnlItemsNumbers[i]!.InnerText.Equals("374857"))
                {
                    /* Once you find that store item, go the node directly 
                     * below (next to) it and add the new attribute to it. */
                    ((XmlElement)(xnlItemsNumbers[i]!.NextSibling)!).SetAttributeNode(xaStoreItem);
                }
            }

            // Save the updated file
            xdStoreItems.Save(strStoreItems);
        }
    }
}

This code would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
    <store-item>
        <item-number>702481</item-number>
        <item-name>Vox Continental 73-key Performance Keyboard</item-name>
        <price>1925.45</price>
    </store-item>
    <store-item>
        <item-number>374857</item-number>
        <item-name hand="left">Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
        <price>194.25</price>
    </store-item>
    <store-item>
        <item-number>538580</item-number>
        <item-name>Mendini By Cecilio Kids Drum Set</item-name>
        <price>512.86</price>
    </store-item>
</musical-instruments>

The Parent of an Attribute

Consider the following XML document:

Guitar
<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
  <store-item>
    <item-number>702481</item-number>
    <item-name>Vox Continental 73-key Performance Keyboard</item-name>
    <price>1925.45</price>
  </store-item>
  <store-item>
    <item-number items-included="1">374857</item-number>
    <item-name hand="right"
			   strings="6"
			   body-material="Mahogany"
			   color="Natural">Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
    <price discount="20">194.25</price>
  </store-item>
  <store-item>
    <item-number>538580</item-number>
    <item-name>Mendini By Cecilio Kids Drum Set</item-name>
    <price>512.86</price>
  </store-item>
</musical-instruments>

Once an attribute has been created, to let you identify the element to which it belongs, the XmlAttribute is equipped with a property named OwnerElement

public virtual System.Xml.XmlElement? OwnerElement { get; }

This property produces an XmlElement value. Here is an example:

using System.Xml;

namespace ApplianceStore1
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            XmlElement? xeStoreItem = null;

            // This is the DOM object of this project
            XmlDocument xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Appliance Store\\StoreItems1.xml";

            // Open the file and put the records in the DOM object
            xdStoreItems.Load(strStoreItems);

            /* Since we need to locate a particular node, 
             * we will check every item by its number. Therefore, 
             * get a list of all items by their items numbers. */
            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            // Visit each item
            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                // Look for a store item whose number is "374857"
                if (xnlItemsNumbers[i]!.InnerText.Equals("374857"))
                {
                    XmlAttributeCollection xacCharacteristics = xnlItemsNumbers[i]?.NextSibling?.Attributes!;

                    foreach(XmlAttribute xacCharacteristic in xacCharacteristics)
                    {
                        if (xacCharacteristic.Name.StartsWith("body"))
                        {
                            xeStoreItem = xacCharacteristic.OwnerElement!;
                        }
                    } 
                }
            }

            if (xeStoreItem != null)
                MessageBox.Show("The parent/owner of the attribute is: " + xeStoreItem.OuterXml,
                                "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("The sought attribute was not found.",
                                "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

This would produce:

Attribute - Parent Owner

Deleting Attributes

Deleting an Attribute by Position

If an element has an attribute you don't want or that you don't need anymore, you can delete that attribute. You have various options, two are available through the XmlElement class.

The attributes of an XmlElement object are considered stored in an indexed poperty with the most left attribute at index 0, the second from left at index 1, and so on. Based on this, to let you remove an attribute by locating it based on its index, the XmlAttribute is equipped with a method named RemoveAttributeAt. Its syntax is:

public virtual XmlNode RemoveAttributeAt(int i);

When calling this method, if an attribute exists at position i, it will be deleted and the method would return it. If there is no attribute at that index, the method doesn't do anything and it returns null. Here is an example:

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            XmlElement? xeStoreItem = null;

            // This is the DOM object of this project
            XmlDocument xdStoreItems = new();
            string strStoreItems = "E:\\Solo Music Store\\StoreItems1.xml";

            // Open the file and put the records in the DOM object
            xdStoreItems.Load(strStoreItems);

            /* Since we need to locate a particular node, 
             * we will check every item by its number. Therefore, 
             * get a list of all items by their items numbers. */
            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            // Visit each item
            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                // Look for a store item whose number is "374857"
                if (xnlItemsNumbers[i]!.InnerText.Equals("374857"))
                {
                    XmlAttributeCollection xacCharacteristics = xnlItemsNumbers[i]?.NextSibling?.Attributes!;

                    foreach(XmlAttribute xacCharacteristic in xacCharacteristics)
                    {
                        if (xacCharacteristic.Name.StartsWith("body"))
                        {
                            xeStoreItem = xacCharacteristic.OwnerElement!;

                            XmlNode xnRemove = xeStoreItem.RemoveAttributeAt(2)!;
                            
                            MessageBox.Show("The " + xnRemove.OuterXml + " node has been removed.",
                                "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // Save the updated file
                            xdStoreItems.Save(strStoreItems);
                            break;
                        }
                    } 
                }
            }
        }
    }
}

This code would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
    <store-item>
        <item-number>702481</item-number>
        <item-name>Vox Continental 73-key Performance Keyboard</item-name>
        <price>1925.45</price>
    </store-item>
    <store-item>
        <item-number items-included="1">374857</item-number>
        <item-name hand="right"
			 strings="6"
             color="Natural">Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
        <price discount="20">194.25</price>
    </store-item>
    <store-item>
        <item-number>538580</item-number>
        <item-name>Mendini By Cecilio Kids Drum Set</item-name>
        <price>512.86</price>
    </store-item>
</musical-instruments>

Attribute Removal

Deleting an Attribute by Name

Using the XmlElement.RemoveAttributeAt() method to delete an attribute can be uncertain because you would not know whether there is an attribute at the specified position. An alternative is to specify the name of the attribute you want to delete. To support this, the XmlElement class is equipped with a method named RemoveAttribute. It is overloaded with two versions. One of the versions of this method uses the following syntax:

public virtual void RemoveAttribute(string name);

This method expects as argument the name of the attribute to remove. Here is an example:

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            XmlElement? xeStoreItem = null;

            var xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Solo Music Store\\StoreItems.xml";

            // Open the file and put the records in the DOM object
            xdStoreItems.Load(strStoreItems);

            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            // Visit each item
            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                if (xnlItemsNumbers[i]!.InnerText.Equals("374857"))
                {
                    XmlAttributeCollection xacCharacteristics = xnlItemsNumbers[i]?.NextSibling?.Attributes!;

                    foreach(XmlAttribute xacCharacteristic in xacCharacteristics)
                    {
                        if (xacCharacteristic.Name.StartsWith("color"))
                        {
                            xeStoreItem = xacCharacteristic.OwnerElement!;

                            xeStoreItem?.RemoveAttribute("color");
                            
                            xdStoreItems.Save(strStoreItems);
                            break;
                        }
                    } 
                }
            }
        }
    }
}

This code would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
    <store-item>
        <item-number>702481</item-number>
        <item-name>Vox Continental 73-key Performance Keyboard</item-name>
        <price>1925.45</price>
    </store-item>
    <store-item>
        <item-number items-included="1">374857</item-number>
        <item-name hand="right"
                   strings="6">Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
        <price discount="20">194.25</price>
    </store-item>
    <store-item>
        <item-number>538580</item-number>
        <item-name>Mendini By Cecilio Kids Drum Set</item-name>
        <price>512.86</price>
    </store-item>
</musical-instruments>

Deleting an Attribute as a Node

Another technique you can use to delete an attribute consists of defining an XmlAttribute object and submitting it to its XmlElement parent to delete. To let you do this, the XmlElement class is equipped with a method named RemoveAttributeNode. Its syntax is:

public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr);

When calling this method, pass an XmlAttribute object as argument. If the attribute exists, it would be removed and the method would return the deleted attribute. If the attribute doesn't exist, nothing would happen. Here is an example:

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            XmlElement? xeStoreItem = null;

            var xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Solo Music Store\\StoreItems1.xml";

            // Open the file and put the records in the DOM object
            xdStoreItems.Load(strStoreItems);

            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            // Visit each item
            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                if (xnlItemsNumbers[i]!.InnerText.Equals("374857"))
                {
                    XmlAttributeCollection xacCharacteristics = xnlItemsNumbers[i]?.NextSibling?.Attributes!;

                    foreach(XmlAttribute xacCharacteristic in xacCharacteristics)
                    {
                        if (xacCharacteristic.Name.StartsWith("hand"))
                        {
                            xeStoreItem = xacCharacteristic.OwnerElement!;

                            XmlAttribute xaRemoved = xeStoreItem?.RemoveAttributeNode(xacCharacteristic)!;
                            
                            xdStoreItems.Save(strStoreItems);

                            MessageBox.Show("The " + xaRemoved.OuterXml + " attribute has been removed.",
                                            "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            break;
                        }
                    } 
                }
            }
        }
    }
}

This code would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
    <store-item>
        <item-number>702481</item-number>
        <item-name>Vox Continental 73-key Performance Keyboard</item-name>
        <price>1925.45</price>
    </store-item>
    <store-item>
        <item-number items-included="1">374857</item-number>
        <item-name strings="6">Fender 6 String CC-60S V2 Mahogany Acoustic Guitar</item-name>
        <price discount="20">194.25</price>
    </store-item>
    <store-item>
        <item-number>538580</item-number>
        <item-name>Mendini By Cecilio Kids Drum Set</item-name>
        <price>512.86</price>
    </store-item>
</musical-instruments>

Attribute Removal

The Collection of Attributes of an Element

Introduction

In the start tag of an element, you can create as many attributes as you judge necessary. Here are examples of elements with attributes:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
  <store-item>
    <item-number>482758</item-number>
    <item-name pickup-configuration="Piezo"
			   number-of-strings="6">Fender Malibu Player Acoustic Guitar</item-name>
    <price>375.48</price>
  </store-item>
  <store-item>
    <item-number items-included="3">820750</item-number>
	  <category>Keyboards</category>
	  <sub-category>Synthesizers</sub-category>
	  <item-name number-of-keys="61">Roland JUNO-DS 61-Key Lightweight Synth-Action Keyboard</item-name>
    <price discount="20">724.65</price>
  </store-item>
  <store-item>
    <item-number>925374</item-number>
    <item-name color="Black"
			   number-of-strings="5"
			   hand-orientation="Right"
			   pickup-configuration="S"
			   neck-material-type="Maple"
			   fretboard-material-type="Rosewood">Yamaha BB235 BB-Series 5-String Bass Guitar</item-name>
    <price discount="20">372.68</price>
  </store-item>
</musical-instruments>

As mentioned already and as you should always remember, attributes belong to an element. To support them, the attributes of an element are stored in the Attributes property of the XmlElement class. The XmlElement.Attributes property is based on a class called XmlAttributeCollection.

To let you get the number of attributes in an element, the XmlAttributeCollection class inherits a property named Count from its parent the XmlNamedNodeMap class:

public virtual int Count { get; }

In the Create a New Project dialog box, under Recent Project Templates, click Windows Forms App (.NET Framework)

using System.Xml;

namespace SoloMusicStore
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            var xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Solo Music Store\\StoreItems1.xml";

            xdStoreItems.Load(strStoreItems);

            XmlNodeList xnlStoreItems = xdStoreItems.GetElementsByTagName("item-name");

            foreach(XmlNode xnStoreItem in xnlStoreItems)
            {
                if(xnStoreItem.Attributes!.Count == 1)
                    MessageBox.Show("The \"" + xnStoreItem.InnerText + "\" element contains " + 
                                    " 1 attribute.",
                                    "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("The \"" + xnStoreItem.InnerText + "\" element contains " +
                                    xnStoreItem.Attributes!.Count.ToString() + " attributes.",
                                    "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

This would produce:

Attribute - Parent Owner

Attribute - Parent Owner

Attribute - Parent Owner

Adding the First Attribute

Whether using its index or name, after accessing an attribute, you can manipulate it as you see fit. For example, you can change or delete it using the same techniques we saw to perform on an individual attribute.

As mentioned already, the attributes are stored as a list. Because you have complete access to this list and the positions of its attributes, when creating or adding a new attribute, you can specify the position the new attribute should have in the collection. To let you create an attribute as the first in an element, the XmlAttributeCollection class is equipped with a method named Prepend. Its syntax is:

public virtual XmlAttribute Prepend(XmlAttribute node);

This method expects an XmlAttribute as argument. If that attribute exists in the collection of attributes of its parent, the method deletes that attribute and returns that attribute. Here is an example:

using System.Xml;

namespace ApplianceStore1
{
    public partial class Management : Form
    {
        public Management()
        {
            InitializeComponent();
        }

        private void Management_Load(object sender, EventArgs e)
        {
            var xdStoreItems = new XmlDocument();
            string strStoreItems = "E:\\Appliance Store\\StoreItems1.xml";

            xdStoreItems.Load(strStoreItems);

            XmlNodeList xnlItemsNumbers = xdStoreItems.GetElementsByTagName("item-number");

            for (int i = 0; i < xnlItemsNumbers.Count; i++)
            {
                if (xnlItemsNumbers[i]!.InnerText.Equals("702481"))
                {
                    if (xnlItemsNumbers[i]!.InnerText.Equals("820750"))
                    {
                        XmlAttribute xaStoreItem = xdStoreItems.CreateAttribute("level");
                        xaStoreItem.Value = "Introductory";

                        XmlAttribute xaAdded = xnlItemsNumbers[i]!.Attributes!.Prepend(xaStoreItem);

                        xdStoreItems.Save(strStoreItems);

                        MessageBox.Show("The " + xaAdded.OuterXml + " attribute has been added.",
                                        "Solo Music Store", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        break;
                    }

                }
            }
        }
    }
}

This code would result in:

<?xml version="1.0" encoding="utf-8"?>
<musical-instruments introduction="Solo Music Store">
  <store-item>
    <item-number>482758</item-number>
    <item-name pickup-configuration="Piezo"
			 number-of-strings="6">Fender Malibu Player Acoustic Guitar</item-name>
    <price>375.48</price>
  </store-item>
  <store-item>
    <item-number level="Introductory"
				items-included="1">820750</item-number>
    <category>Keyboards</category>
    <sub-category>Synthesizers</sub-category>
    <item-name number-of-keys="61">Roland JUNO-DS 61-Key Lightweight Synth-Action Keyboard</item-name>
    <price discount="20">724.65</price>
  </store-item>
  <store-item>
    <item-number>925374</item-number>
    <item-name color="Black"
			 number-of-strings="5"
			 hand-orientation="Right"
			 pickup-configuration="S"
			 neck-material-type="Maple"
			 fretboard-material-type="Rosewood">Yamaha BB235 BB-Series 5-String Bass Guitar</item-name>
    <price discount="20">372.68</price>
  </store-item>
</musical-instruments>

Attribute Removal

Inserting an Attribute Before Another

Another technique you can use consists of locating an attribute first. Once you have one, to create a new attribute before it, you can call the XmlAttributeCollection.InsertBefore() method. Its syntax is:

public virtual XmlAttribute InsertBefore(XmlAttribute newNode,
					 XmlAttribute refNode);

To add a new attribute after the current one, you can call the XmlAttributeCollection.InsertAfter() method. Its syntax is:

public virtual XmlAttribute InsertAfter(XmlAttribute newNode,
					XmlAttribute refNode);

To add an attribute at the end of the list of attributes of an element, you can call the XmlAttributeCollection.Append() method. Its syntax is:

public virtual XmlAttribute Append(XmlAttribute node); 

Access to an XML Attribute

To access an attribute by its position in the collection, you can use the XmlNamedNodeMap.Item() method.

The XmlAttributeCollection class is equipped with an ItemOf indexed property. This property is overloaded in three versions. The first version has the following syntax:

public virtual XmlAttribute this[int i] {get;}

This property allows you to access an attribute by considering that the attributes are stored in an array. The first or most left attribute has an index of 0; the second attribute from left (of course without counting the name of the element) has an index of 1, and so on.

It can be difficult and sometimes unpredictable, in some scenarios, to access an attribute by its index because you must know exactly where each attribute is positioned. Consider the following XML document:

<?xml version="1.0" encoding="utf-8" ?>
<videos FileDesc="Personal Video Collection">
    <video ISBN="0-7888-1623-3"
	   ScreenRatio="Standard"
	   SoundtrackAvailable="True">
        <title StoryBy="Marty Kaplan and Jonathan Reynold"
	       Screenplay="Marty Kaplan">The Distinguished Gentleman</title>
        <director>Jonathan Lynn</director>
        <actors></actors>
        <length>112 Minutes</length>
        <format>DVD</format>
        <rating>R</rating>
    </video>
    <video ISBN="0-7907-3900-3">
        <title Screenplay="Charlie Peter">Her Alibi</title>
        <director>Bruce Beresford</director>
        <length>94 Mins</length>
        <format>DVD</format>
        <rating>PG-13</rating>
    </video>
</videos>

In the first video, the name of the screenplay writer is stored at index 1. In the second video, the name of the screenplay writer is stored at index 0. In this case, it may not be a good item to use the index to locate an attribute. Fortunately, the second version of the overloaded XmlAttributeCollection.ItemOf[] property has the following syntax:

public virtual XmlAttribute this[string name] {get;}

With this version, you can explicitly specify the name of the attribute that you want.

Attribute Removal

Using the list of attributes of an element, you can delete one or all attributes of an element. Since the attributes are stored in a collection, you can locate the undesired attribute by its index and then delete it. To do this, you can call the XmlAttributeCollection.RemoveAt() method. Its syntax is:

public virtual XmlAttribute RemoveAt(int i);

This method expects the index of the attribute that needs to be removed. As mentioned for the XmlAttributeCollection.ItemOf indexed property, to efficiently use this RemoveAt() method, you should know the exact index of the attribute, otherwise, you may access and therefore delete the wrong attribute. An alternative is to explicitly identify the attribute you want to delete. To do this, you can call the XmlAttributeCollection.Remove() method. Its syntax is:

public virtual XmlAttribute Remove(XmlAttribute node);

This method takes as attribute the XmlAttribute identification of the attribute you want to remove.

To delete all attributes of an element, you can call the XmlAttributeCollection.RemoveAll() method. Its syntax is:

public virtual void RemoveAll();

This method would simply remove all attributes that belong to an XmlElement object.

     

Previous Copyright © 2005-2023, FunctionX Monday 06 December 2021 Next