Home

XML Elements Fundamentals

 

Introduction

An element in an XML document is an object that begins with a start-tag, may contain a value, and may terminate with an end-tag. Based on this, the combination of a start-tag, the value, and the end-tag is called an element. An element can be more than that but for now, we will consider that an element is primarily characterized by a name and possibly a value.

To support XML elements, the System.Xml namespace provides the XmlElement class. XmlElement is based on a class named XmlLinkedNode that itself is based on XmlNode. To access an XML element, you can declare a variable of type XmlElement but the main purpose of this class is to get an element from a DOM object. For this reason, the XmlElement class doesn't have a constructor you can use. Instead, and as we will learn, the other classes have methods that produce an XmlElement element you can manipulate as necessary.

In the previous lesson, we saw that every XML file must have a root and we mentioned that you could call the XmlDocument.DocumentElement property to access it. This property is of type XmlElement and, to access it, you can declare an XmlElement variable and assign it this property. 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 elm = xmlDoc.DocumentElement;
                Console.WriteLine("{0}", elm);
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

This would produce:

System.Xml.XmlElement

Press any key to continue . . .

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

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))
            {
                XmlTextReader rdrXml = new XmlTextReader(strFilename);

                do {
                    switch (rdrXml.NodeType)
                    {
                        case XmlNodeType.Element:
                            break;
                    }
                }while (rdrXml.Read());
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

Practical Learning Practical Learning: Introducing XML Elements

  1. Start Microsoft Visual C# and create a Console Application named CollegeParkAutoParts2
  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
     
  8. Click Save

The Name of an Element

The name of an element is the string that represents the tag. For example, in <Director>, the word Director is the name of the element. An element must have at least a start-tag. All of the tags we have seen so far were created as elements. When creating your elements, remember to follow the rules we defined for names.

The XmlElement class is equipped with the Name property that can be used to identify an existing element. Here is an example of accessing it:

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 elm = xmlDoc.DocumentElement;
                Console.WriteLine("{0}", elm.Name);
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

This would produce:

Videos

Press any key to continue . . .

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

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))
            {
                XmlTextReader rdrXml = new XmlTextReader(strFilename);

                do {
                    switch (rdrXml.NodeType)
                    {
                        case XmlNodeType.Element:
                            Console.WriteLine("{0}", rdrXml.Name);
                            break;
                    }
                }while (rdrXml.Read());
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

This would produce:

Videos
Video
Title
Director
Length
Format
Rating
Video
Title
Director
Length
Format
Rating
Video
Title
Director
Length
Format
Rating

Press any key to continue . . .

The Text or Value of an Element

The value of an element is the item displayed on the right side of the start-tag. It is also called the text of the element. In the case of <Director>Jonathan Lynn</Director>, the "Jonathan Lynn" string is the value of the Director element. To support the text or value of an element, the XmlElement class is equipped with the Value property.

While the value of one element can be a number, the value of another element can be a date. Yet another element can use a regular string as its value. Consider the following example:

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
	<Employee>
		<FullName>Lydia Thomason</FullName>
		<Salary>25.64</Salary>
		<DepartmentID>1</DepartmentID>
	</Employee>
	<Employee>
		<FullName>June Grath</FullName>
		<Salary>16.38</Salary>
		<DepartmentID>4</DepartmentID>
	</Employee>
</Employees>

Notice that the Salary elements contain numbers that look like currency values and the DepartmentID elements use an integer as value.

If you are using an XmlTextReader object to scan a file, when the Read() method gets to an element, you can find out what its value is by accessing this property. Here is an example:

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))
            {
                XmlTextReader rdrXml = new XmlTextReader(strFilename);

                do {
                    switch (rdrXml.NodeType)
                    {
                        case XmlNodeType.Text:
                            Console.WriteLine("{0}", rdrXml.Value);
                            break;
                    }
                }while (rdrXml.Read());
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

This would produce:

The Distinguished Gentleman
Jonathan Lynn
112 Minutes
DVD
R
Her Alibi
Bruce Beresford
94 Mins
DVD
PG-13
Chalte Chalte
Aziz Mirza
145 Mins
DVD
N/R

Press any key to continue . . .

The value or text of an element is an object of type XmlText.

 

Practical Learning Practical Learning: Getting the Text of an Element

  1. Access the Program.cs file and change it as follows::
     
    using System;
    using System.IO;
    using System.Xml;
    
    namespace CollegeParkAutoParts2
    {
        class Program
        {
            static int Main(string[] args)
            {
                FileStream fsCPAP = null;
                string strFilename = "makes.xml";
                XmlDocument xmlDoc = new XmlDocument();
    
                if (File.Exists(strFilename))
                {
                    fsCPAP = new FileStream(strFilename,
                                            FileMode.Open,
                                            FileAccess.Read);
                    XmlTextReader rdrXml = new XmlTextReader(fsCPAP);
    
                    do
                    {
                        switch (rdrXml.NodeType)
                        {
                            case XmlNodeType.Text:
                                Console.WriteLine("Make: {0}",
                                                  rdrXml.Value);
                                break;
                        }
                    } while (rdrXml.Read());
                }
                else
                    Console.WriteLine("The {0} file was not found",
                                      strFilename);
    
                Console.WriteLine();
                return 0;
            }
        }
    }
  2. Execute the application to see the result. This would produce:
     
    Make: Acura
    Make: Audi
    Make: BMW
    Make: Chevrolet
    
    Press any key to continue . . .
  3. Close the DOS window

Empty Elements

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

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

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

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 elm = xmlDoc.DocumentElement;
                Console.WriteLine("{0}", elm.Value);
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

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

This would produce:


Press any key to continue . . .

Because the Videos node doesn't have its own value, its Value property returns an empty string.

Character Entities in an Element Value

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

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

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

An XML file in a browser

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

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

This would produce:

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

Code Symbol Code Symbol Code Symbol Code Symbol Code Symbol
&apos; ' &#067; C &#106; j &#179; &#218;
&lt; < &#068; D &#107; k &#180; &#219;
&gt; > &#069; E &#108; l &#181; &#220;
&amp; & &#070; F &#109; m &#182; &#221;
&quot; " &#071; G &#110; n &#183; &#222;
&#033; ! &#072; H &#111; o &#184; &#223;
&#034; " &#073; I &#112; p &#185; &#224;
&#035; # &#074; J &#113; q &#186; &#225;
&#036; $ &#075; K &#114; r &#187; &#226;
&#037; % &#076; L &#115; s &#188; &#227;
&#038; & &#077; M &#116; t &#189; &#228;
&#039; ' &#078; N &#117; u &#190; &#229;
&#040; ( &#079; O &#118; v &#191; &#230;
&#041; ) &#080; P &#119; w &#192; &#231;
&#042; * &#081; Q &#120; x &#193; &#232;
&#043; + &#082; R &#121; y &#194; &#233;
&#044; , &#083; S &#122; z &#195; &#234;
&#045; - &#084; T &#123; { &#196; &#235;
&#046; . &#085; U &#125; } &#197; &#236;
&#047; / &#086; V &#126; ~ &#198; &#237;
&#048; 0 &#087; W &#160; empty &#199; &#238;
&#049; 1 &#088; X &#161; &#200; &#239;
&#050; 2 &#089; Y &#162; &#201; &#240;
&#051; 3 &#090; Z &#163; &#202; &#241;
&#052; 4 &#091; [ &#164; &#203; &#242;
&#053; 5 &#092; \ &#165; &#204; &#243;
&#054; 6 &#093; ] &#166; &#205; &#244;
&#055; 7 &#094; ^ &#167; &#206; &#245;
&#056; 8 &#095; _ &#168; &#207; &#246;
&#057; 9 &#096; ` &#169; &#208; &#247;
&#058; : &#097; a &#170; &#209; &#248;
&#059; ; &#098; b &#171; &#210; &#249;
&#060; < &#099; c &#172; &#211; &#250;
&#061; = &#100; d &#173; &#212; &#251;
&#062; > &#101; e &#174; &#213; &#252;
&#063; ? &#102; f &#175; &#214; &#253;
&#064; @ &#103; g &#176; &#215; &#254;
&#065; A &#104; h &#177; &#216; &#255;
&#066; B &#105; i &#178; &#217; &#256; A

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

 

Practical Learning Practical Learning: Introducing XML Elements

  1. In the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> New Item...
  2. In the Templates list, make sure XML File is selected.
    Set the Name to models and click Add
  3. To save the file, on the main menu, click File -> Save models.xml As...
  4. 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
  5. 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>
  6. Access the Program.cs file and modify it as follows:
     
    using System;
    using System.IO;
    using System.Xml;
    
    namespace CollegeParkAutoParts2
    {
        class Program
        {
            static int Main(string[] args)
            {
                FileStream fsCPAP = null;
                string strFilename = "models.xml";
                XmlDocument xmlDoc = new XmlDocument();
    
                if (File.Exists(strFilename))
                {
                    fsCPAP = new FileStream(strFilename,
                                            FileMode.Open,
                                            FileAccess.Read);
                    XmlTextReader rdrXml = new XmlTextReader(fsCPAP);
    
                    do
                    {
                        switch (rdrXml.NodeType)
                        {
                            case XmlNodeType.Text:
                                Console.WriteLine("Model: {0}",
                                                  rdrXml.Value);
                                break;
                        }
                    } while (rdrXml.Read());
                }
                else
                    Console.WriteLine("The {0} file was not found",
                                      strFilename);
    
                Console.WriteLine();
                return 0;
            }
        }
    }
  7. Execute the application to see the result:
     
    Model: NSX
    Model: TL
    Model: Spider
    Model: A4
    Model: RS6
    Model: 323I
    Model: M5
    Model: Astro
    Model: Cavalier
    Model: Protg
    
    Press any key to continue . . .
  8. Close the DOS window
 

Previous Copyright © 2006 FunctionX, Inc. Next