Home

Introduction to XML Elements

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.

To support XML elements, the System.Xml namespace provides the XmlElement class. 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.

We know that every XML file must have a root and you can use 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.

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.

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 for names in XML.

The XmlElement class is equipped with the Name property that can be used to identify an existing element:

Public Overrides ReadOnly Property Name As String

Consider the following XML file named PeriodicTable.xml:

<?xml version="1.0" encoding="utf-8"?>
<chemistry>
  <element>
    <atomic-number>1</atomic-number>
    <element-name>Hydrogen</element-name>
    <symbol>H</symbol>
    <atomic-mass>1.0079</atomic-mass>
  </element>
  <element>
    <atomic-number>2</atomic-number>
    <element-name>Helium</element-name>
    <symbol>He</symbol>
    <atomic-mass>4.002682</atomic-mass>
  </element>
  <element>
    <atomic-number>3</atomic-number>
    <element-name>Lithium</element-name>
    <symbol>Li</symbol>
    <atomic-mass>6.941</atomic-mass>
  </element>
  <element>
    <atomic-number>4</atomic-number>
    <element-name>Berylium</element-name>
    <symbol>Be</symbol>
    <atomic-mass>9.0122</atomic-mass>
  </element>
  <element>
    <atomic-number>5</atomic-number>
    <element-name>Boron</element-name>
    <symbol>B</symbol>
    <atomic-mass>10.811</atomic-mass>
  </element>
</chemistry>

Here is an example of accessing it:

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry - Periodic Table</title>
</head>
<body>
<h3>Chemistry - Periodic Table</h3>

<%
    Dim xeElement As XmlElement
    Dim xdChemistry As New XmlDocument()
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFileName) Then
        Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
            xdChemistry.Load(fsVideo)

            xeElement = xdChemistry.DocumentElement

            Response.Write(xeElement.Name)
        End Using
    Else
        Response.Write("The file " + strFileName + " was not found")
    End If
%>

</body>
</html>

This would produce:

Chemistry - Periodic Table

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 by accessing it. Here is an example:

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>

<%
    Dim rdrChemistry As XmlTextReader
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFileName) Then
        rdrChemistry = New XmlTextReader(strFilename)

        Do
            Select Case rdrChemistry.NodeType
                Case XmlNodeType.Element
                     Response.Write("<br>" & rdrChemistry.Name)
            End Select
        Loop While rdrChemistry.Read
    Else
        Response.Write("The file " + strFileName + " was not found.")
    End If
%>

</body>
</html>

This would produce:

The Name of an Element

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:

Public Overridable Property Value As String

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 XML file named PeriodicTable.xml:

<?xml version="1.0" encoding="utf-8"?>
<chemistry>
  <element>
    <atomic-number>1</atomic-number>
    <element-name>Hydrogen</element-name>
    <symbol>H</symbol>
    <atomic-mass>1.0079</atomic-mass>
  </element>
  <element>
    <atomic-number>2</atomic-number>
    <element-name>Helium</element-name>
    <symbol>He</symbol>
    <atomic-mass>4.002682</atomic-mass>
  </element>
  <element>
    <atomic-number>3</atomic-number>
    <element-name>Lithium</element-name>
    <symbol>Li</symbol>
    <atomic-mass>6.941</atomic-mass>
  </element>
  <element>
    <atomic-number>4</atomic-number>
    <element-name>Berylium</element-name>
    <symbol>Be</symbol>
    <atomic-mass>9.0122</atomic-mass>
  </element>
  <element>
    <atomic-number>5</atomic-number>
    <element-name>Boron</element-name>
    <symbol>B</symbol>
    <atomic-mass>10.811</atomic-mass>
  </element>
</chemistry>

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:

<%@ Page Language= "VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>

<%
    Dim rdrChemistry As XmlTextReader
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFileName) Then
        rdrChemistry = New XmlTextReader(strFileName)

        Do
            Select Case rdrChemistry.NodeType
                Case XmlNodeType.Text
                    Response.Write("<br>" & rdrChemistry.Value)
            End Select
        Loop While rdrChemistry.Read
    Else
        Response.Write("The file " + strFileName + " was Not found.")
    End If
%>

</body>
</html>

This would produce:

The Text or Value of an Element

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

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.

Character Entities in an Element Value

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

<?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.

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>

Here is a list of some 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; Ā

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

Identifying the Markup of a Node

The Inner Text of a node

The combined text of the values of the children of a node is available through its XmlNode.InnerText property which is declared as follows:

Public Overridable Property InnerText As String

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

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>

<%
    Dim xeElement As XmlElement
    Dim xdChemistry As New XmlDocument()
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFileName) Then
        Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
            xdChemistry.Load(fsVideo)

            xeElement = xdChemistry.DocumentElement

            Response.Write("<br>" & xeElement.InnerText)
        End Using
    Else
        Response.Write("The file " + strFileName + " was not found.")
    End If
%>

</body>
</html>

This would produce:

The Inner Text of a node

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

The Outer XML Code of a Node

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

Public Overridable ReadOnly Property OuterXml As String

The Inner XML Code of a Node

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

Public Overridable Property InnerXml As String

Here is an example:

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>

<%
    Dim xeElement As XmlElement
    Dim xdChemistry As New XmlDocument()
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFilename) Then
        Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
            xdChemistry.Load(fsVideo)

            xeElement = xdChemistry.DocumentElement

            Response.Write("<br>" & xeElement.InnerXml)
        End Using
    Else
        Response.Write("The file " & strFilename & "  was not found")
    End If
%>

</body>
</html>

The Child Nodes of a Node

Introduction

As mentioned already, a node can be nested inside of another. A node can have as many children as necessary, making them child nodes of the parent node. Consider the following XML document:

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

The title and the director nodes are children of the video node. The video node is the parent of both the title and the director nodes.

A Collection of XML Nodes

As you may know already, an XML document usually contains many nodes. To consider a collection of nodes, the .NET Framework provides a class named XmlNodeList. It starts as follows:

Public MustInherit Class XmlNodeList
	Implements IEnumerable, IDisposable

Notice that the XmlNodeList implements the IDisposable interface. This means that its variable consumes resources and that variable should (must) be closed at the end of its section. As you may remember, the alternative is to include its code in a Using section.

Linking the Nodes

To manage the relationships among the nodes of an XML document, the .NET Framework provides a class named XmlLinkedNode:

Public MustInherit Class XmlLinkedNode
	Inherits XmlNode

Many classes derive from XmlLinkedNode. That's the case for the XmlElement class:

Public Class XmlElement
	Inherits XmlLinkedNode

A Collection of Child Nodes

Introduction

To support the child nodes of a particular node, the XmlNode class is equipped with a property named ChildNodes. That property is of type XmlNodeList. The property is declared as follows:

Public Overridable ReadOnly Property ChildNodes As XmlNodeList

When this property is used, it produces an XmlNodeList list, which is a collection of all nodes that share the same parent. Each item in the collection is of type XmlNode.

The Number of Child Nodes of a Node

To give you the number of nodes on an XmlNodeList collection, the class is equipped with a property named Count. Here is an example:

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>

<%
    Dim xeElement As XmlElement
    Dim xnlElements As XmlNodeList
    Dim xdChemistry As New XmlDocument()
    Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")

    If File.Exists(strFilename) Then
        Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
            xdChemistry.Load(fsVideo)
            xeElement = xdChemistry.DocumentElement
            xnlElements = xeElement .ChildNodes

            Response.Write("The root element contains " & xnlElements.Count & "  nodes.")
        End Using
    Else
        Response.Write("The file " & strFilename & "  was not found")
    End If
%>

</body>
</html>

This would produce:

The Number of Child Nodes of a Node


Previous Copyright © 2002-2016 FunctionX Next