Introduction to XML Attributes

Overview

As you should know already, an XML attribute is a type of element that is created or included in the start tag of a node. Here are examples of attributes in an XML document of a file named Videos.xml:

<?xml version="1.0" encoding="utf-8"?>
<videos common-name="Video Collection" purpose="To keep track of personal/home videos">
  <video shelf-number="CMD97904">
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video shelf-number="PLT24857">
    <title France="Monsieur le D&#233;put&#233;" Italy="Il Distinto Gentiluomo" Spain="Su Distinguida Señoría">The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <cast-members>
      <actor role="Thomas Jefferson Johnson">Eddie Murphy</actor>
      <actor role="Dick Dodge">Lane Smith</actor>
      <actor role="Miss Loretta">Sheryl Lee Ralph</actor>
      <actor role="Olaf Andersen">Joe Don Baker</actor>
      <actor role="Celia Kirby">Victoria Rowell</actor>
    </cast-members>
    <cast-members>
      <actor role="Elijah Hawkins">Charles S. Dutton</actor>
      <actor role="Arthur Reinhardt">Grant Shaud</actor>
      <actor role="Terry Corrigan">Kevin McCarthy</actor>
      <actor role="Armando">Victor Rivers</actor>
      <actor role="Homer">Chi McBride</actor>
      <actor role="Zeke Bridges">Noble Willingham</actor>
    </cast-members>
    <length>112</length>
    <format screen="Wide Screen">DVD</format>
    <rating>R</rating>
    <year-released date-released="4 December 1992">1992</year-released>
    <categories>
      <genre>Comedy</genre>
      <genre>Politics</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>government</keyword>
        <keyword>con artist</keyword>
        <keyword>lobbyist</keyword>
        <keyword>election</keyword>
      </keywords>
    </categories>
  </video>
  <video>
    <title>Duplex</title>
    <director>Danny DeVito</director>
    <cast-members>
      <narrator>Danny DeVito</narrator>
    </cast-members>
  </video>
  <video shelf-number="SCF13948">
    <title Spain="El Día de Mañana" Croatia="Dan Poslije Sutra" Portugal="O Dia Depois de Amanhã">The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124</length>
    <categories>
      <genre>Drama</genre>
      <genre>Environment</genre>
      <genre>Science Fiction</genre>
    </categories>
    <format>BD</format>
    <rating>PG-13</rating>
    <keywords>
      <keyword>climate</keyword>
      <keyword>global warming</keyword>
      <keyword>disaster</keyword>
      <keyword>new york</keyword>
    </keywords>
  </video>
  <video shelf-number="CMD93805">
    <title>Other People's Money</title>
    <director>Alan Brunstein</director>
    <year-released date-released="18 October 1991">1991</year-released>
    <cast-members>
      <actor role="Lawrence Garfield">Danny DeVito</actor>
      <actor role="Andrew Jorgenson">Gregory Peck</actor>
      <actor role="Kate Sullivan">Penelope Ann Miller</actor>
    </cast-members>
    <cast-members>
      <actor role="Bill Coles">Dean Jones</actor>
      <actor role="Bea Sullivan">Piper Laurie</actor>
    </cast-members>
    <categories>
      <genre>Comedy</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>female stocking</keyword>
        <keyword>seduction</keyword>
      </keywords>
      <genre>Business</genre>
      <keywords>
        <keyword>capitalism</keyword>
        <keyword>corporate take-over</keyword>
        <keyword>factory</keyword>
        <keyword>speech</keyword>
        <keyword>public speaking</keyword>
      </keywords>
      <genre>Drama</genre>
      <keywords>
        <keyword>play</keyword>
        <keyword>hostile take-over</keyword>
        <keyword>corporate raider</keyword>
      </keywords>
    </categories>
  </video>
</videos>

Practical LearningPractical Learning: Introducing XML Attributes

  1. Start Microsoft Visual Studio
  2. Create a Windows Forms App named XPathAttributes

Accessing an Attribute

To access an attribute, follow the name of its parent tag with a forward slash, an @ sign, and the name of the attribute. For example, if the root node has an attribute, use the formula:

/root-name/@attribute-name");

Here is an example:

using System.Xml; 

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnVideos_Click(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();

            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/@common-name")!;

            foreach(XmlNode xnVideo in xnlVideos)
            {
                 MessageBox.Show(xnVideo.OuterXml,
                                 "Video Collection",
                                 MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

This would produce:

Introduction to XPath and XML Attributes

In the same way, use any of the formulas we have seen so far to access any node. Then, if the node has an attribute, use the @ sign to get that attribute. Here is an example:

using System.Xml; 

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnVideos_Click(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();

            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/@shelf-number")!;

            foreach(XmlNode xnVideo in xnlVideos)
            {
                lbxAttributes.Items.Add(xnVideo.OuterXml);
            }
        }
    }
}

This would produce:

Introduction to XPath and XML Attributes

If you use an attribute that either doesn't exist or the element doesn't have that particular attribute, the result would be empty; no exception would be thrown.

Getting all Attributes of an Element

If you want to get all the attributes of an element, replace the name of the attribute with * as in @*. Here is an example:

using System.Xml;

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnVideos_Click(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();

            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/title/@*")!;

            foreach(XmlNode xnVideo in xnlVideos)
            {
                lbxActorsRoles.Items.Add(xnVideo.OuterXml);
            }
        }
    }
}

This would produce:

Getting all Attributes of an Element

The Characteristics of an Attribute

Getting the Value of an Attribute

As we have seen so far, both the XPath language and the NET Framework provide various means to access an attribute. For example, the XPath language uses the @ sign to access an XML attribute while the XmlNode class is equipped with the OuterXml, the InnerXml, and the InnerText properties. Here is an example that uses the XmlNode.InnerXml property to access the attribute:

using System.Xml;

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnVideos_Click(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();
            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/cast-members/actor/@role")!;

            foreach(XmlNode xnVideo in xnlVideos)
            {
                lbxActorsRoles.Items.Add(xnVideo.OuterXml);
            }
        }
    }
}

This would produce:

Getting the Value of an Attribute

Remember that, to get all attributes, you can use @* as in:

using System.Xml;

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void Exercise_Load(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();

            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/cast-members/actor/@*")!;

            foreach (XmlNode xnVideo in xnlVideos)
            {
                lbxAttributes.Items.Add(xnVideo.InnerXml);
            }
        }
    }
}

This would produce:

Getting the Value of an Attribute

Notice that the XmlNode.InnerXml property applied to an attribute produces only the text of the attribute. In the same way, you can use the XmlNode.InnerText property to get the same result. On the other hand, the XmlNode.OuterXml property produces the name and value of an attribute.

Getting an Attribute and its Parent

In some cases, you may want to get both the attribute and its parent. To do that, after the name of the element, include the @ and name of the attribute in square brackets. Here is an example:

using System.Xml;

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void Exercise_Load(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();
            xdVideos.Load("../../../Videos.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos =	xeVideo.SelectNodes("/videos/video/cast-members/actor[@role]")!;

            foreach(XmlNode xnVideo in xnlVideos)
            {
                lbxActorsRoles.Items.Add(xnVideo.OuterXml);
            }
        }
    }
}

This would produce:

Getting an Attribute and its Parent

Getting all Attributes and their Parents

If you want to get all attributes and their parent, remember that you can use * in place of the name of the attribute. Here is an example:

using System.Xml;

namespace VideoCollection1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnVideos_Click(object sender, EventArgs e)
        {
            XmlDocument xdVideos = new XmlDocument();

            xdVideos.Load("../../../Videos1.xml");

            XmlElement xeVideo = xdVideos.DocumentElement!;
            XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/title[@*]")!;

            foreach (XmlNode xnVideo in xnlVideos)
            {
                MessageBox.Show(xnVideo.OuterXml,
                                "Video Collection",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

This would produce:

Getting an Attribute and its Parent

Getting an Attribute and its Parent

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2014-2024, FunctionX Friday 28 June 2024, 09:58 Home