XML Elements
XML documents contain XML elements.
What is an XML Element?
An XML element refers to the part from (and including) the start tag to (and including) the end tag.
An element can contain:
- Other elements
- Text
- Attributes
- Or a mix of all the above...
<bookstore> <book category="CHILDREN"> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title>Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
In the example above, <bookstore> and <book> have element content because they contain other elements. The <book> element also has attributes (category="CHILDREN"). The <title>, <author>, <year>, and <price> elements have text content because they contain text.
XML Naming Rules
XML elements must follow these naming rules:
- Names can contain letters, digits, and other characters
- Names cannot start with a digit or punctuation character
- Names cannot start with the letters xml (or XML, Xml, etc.)
- Names cannot contain spaces
You can use any name, with no reserved words.
Best Naming Practices
Make names descriptive. Using underscores is also a good practice: <first_name>, <last_name>.
Names should be short and simple, like <book_title>, rather than <the_title_of_the_book>.
Avoid the "-" character. If you name something "first-name", some software might think you want to subtract name from first.
Avoid the "." character. If you name something "first.name", some software might think "name" is an attribute of the object "first".
Avoid the ":" character. Colons are used for namespaces (explained later).
XML documents often correspond to a database, where fields match elements in the XML document. A practical tip is to use database naming conventions for elements in the XML document.
In XML, non-English letters like éòá are perfectly legal, but be aware of potential issues if your software vendor does not support these characters.
XML Elements Are Extensible
XML elements are extensible to carry more information.
Consider the following XML example:
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
Imagine we create an application that extracts the <to>, <from>, and <body> elements from the XML document and produces the following output:
| MESSAGE To: Tove<br> From: Jani Don't forget me this weekend! |
Now, suppose the author of the XML document adds some extra information:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Would this application break or crash?
No. The application would still find the <to>, <from>, and <body> elements in the XML document and produce the same output.
One of the advantages of XML is that it can be extended without breaking applications.