Similar to an HTML document, an XML document also contains tags.
The main components of an XML document are elements, attributes, and comments.
Elements are used to mark up parts (sections) of an XML document and have the following syntax:
<Element> Content </Element>
Here <Element> is the start tag, </Element> is the end tag, and Content is the value of the element.
For example:
<name> Walkenbach </name>
The content refers to character data, while the elements belong to the markup of the document. In turn, character data is divided into Parsed Character Data (PCDATA) and Unparsed Character Data.
Elements may have no content. For example:
<cellphone></cellphone>
In this case, they can be combined into one tag:
<cellphone/>
Elements may also be nested inside other elements:
<employee> <name> Walkenbach </name> <salary> 10000 </salary> </employee>
Attributes can be assigned to elements to provide additional information and to shorten the code.
An attribute is a name=value pair placed inside the opening tag.
For example, currency is an attribute of the <salary> tag:
<salary currency="USD"> 10000 </salary>
Or the <person> element could be written using attributes as follows.
Using attributes in XML code
<employee> <person lastname="Garnaev" firstname="Andrej" email="garnaev@yandex.ru"/> <person lastname="Rudikova" firstname="Lada" email="rudikowa@gmail.com"/> </employee>
In addition, attributes allow elements to be divided into categories.
For example, in the following code (Listing 10.2, see also file 1-Example.xml on the CD), depending on the value of the type attribute in the <person> element, the information is either confidential or public.
Categorizing elements using attributes
<?xml version="1.0" standalone="yes" ?> <employee> <person type="work"> <lastname>Bond</lastname> <firstname>James</firstname> <email>bond007@yandex.com</email> </person> <person type="work"> <lastname>Cooper</lastname> <firstname>Gary</firstname> <email>gcooper@yandex.com</email> </person> <person type="personal"> <lastname>Cooper</lastname> <firstname>Gary</firstname> <marriedstatus>new married</marriedstatus> <homephone>354-56-56</homephone> </person> </employee>
Comments in XML are written as follows:
<!-- Example of a comment -->