An XML document contains XML Elements.
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
An element can contain:
In the example above, <bookstore> and <book> have element contents, because they contain other elements. <book> also has an attribute (category="CHILDREN"). <title>, <author>, <year>, and <price> have text content because they contain text.
An element with no content is said to be empty.
In XML, you can indicate an empty element like this:
or you can use an empty tag, like this (this sort of element syntax is called self-closing):
The two forms above produce identical results in an XML parser.
Note: Empty elements do not have any content, but they can have attributes!
XML elements must follow these naming rules:
Any name can be used, no words are reserved (except xml).
Create descriptive names, like this: <person>, <firstname>, <lastname>.
Create short and simple names, like this: <book_title> not like this: <the_title_of_the_book>.
Avoid "-". If you name something "first-name", some software may think you want to subtract "name" from "first".
Avoid ".". If you name something "first.name", some software may think that "name" is a property of the object "first".
Avoid ":". Colons are reserved for namespaces (more later).
Non-English letters like éòá are perfectly legal in XML, but watch out for problems if your software doesn't support them.
There are no naming styles defined for XML elements. But here are some commonly used:
|Lower case||<firstname>||All letters lower case|
|Upper case||<FIRSTNAME>||All letters upper case|
|Underscore||<first_name>||Underscore separates words|
|Pascal case||<FirstName>||Uppercase first letter in each word|
|Camel case||<firstName>||Uppercase first letter in each word except the first|
If you choose a naming style, it is good to be consistent!
XML documents often have a corresponding database. A good practice is to use the naming rules of your database for the elements in the XML documents.
XML elements can be extended to carry more information.
Look at the following XML example:
Let's imagine that we created an application that extracted the <to>, <from>, and <body> elements from the XML document to produce this output:
Don't forget me this weekend!
Imagine that the author of the XML document added some extra information to it:
Should the application break or crash?
No. The application should still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output.
One of the beauties of XML, is that it can be extended without breaking applications.