The Attributes of an XML Element



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:

  • Both (must) have a name
  • Each may or may not have a value

The differences between an element and an attribute are:

  • An attribute is considered a characteristic of an element. This means that an attribute belongs to an element
  • An element can have one or more attributes. An attribute cannot have an element
  • An attribute must be created in the start-tag of an element
  • An element cannot be defined as part of an attribute. That is, an attribute is subject to an element and an attribute doesn't own the attribute

Practical Learning Practical Learning: Introducing Attributes 

  1. Create a new Console Application named CountriesStatistics1
  2. To save the file, on the Standard toolbar, click the Save All button
  3. Accept all defaults and click Save
  4. In the Solution Explorer, right-click CountriesStatistics1 -> Add -> New Item...
  5. In the Templates list, click XML File
  6. Set the Name to continents and click Add
  7. Change the file as follows:
    <?xml version="1.0" encoding="utf-8" ?>
  8. To save the file, on the main menu, click File -> Save continents.xml As...
  9. 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

Creating an Attribute

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 that can be used to distinguish it. To specify the name of an attribute, assign a value as a string to its name. Imagine you have an ISBN element as a child of a Video element as follows:


In this case, 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.


Previous Copyright © 2006 FunctionX, Inc. Next