XML Syntax Rules
XML content defines data within tree structures. These structures include elements, indicated by opening and closing tags. Elements can include optional attributes, as well as other elements nested inside them. XML syntax is not typically complex, but it can be easy to create XML content with mistakes in it. Understanding the rules of XML syntax is not generally difficult, making it easier to avoid including errors.
-
Element Tags
-
Each XML element has a name and appears within opening and closing tags. All elements in XML must be properly closed. The following sample XML code demonstrates a correctly closed element:
<person>Max</person>
Some elements can close themselves, rather than the closing tag appearing after the element content. The following is an example of a self-closing element:
<img src="pic.jpg"/>
This is the image tag in XHTML, used for including images in Web pages. In earlier versions of HTML, some elements did not need to be closed properly. XHTML is an example of XML, so elements need to be closed, as in any well-formed XML content.
Attributes
-
XML elements can have attributes. Attributes provide additional information about an element, appearing within the element's opening tag. Attribute values must appear within quotes, as in the following sample markup code:
<person gender="male">Jim</person>
An attribute must have a name and a value. A common error in XML is to include an attribute without placing the value between quotes, as in the following incorrect example:
<person gender=male>Jim</person>
This is not well-formed XML, so may generate errors if it forms part of an application.
-
Nesting
-
XML elements can include other elements inside them, in nested structures. The following sample markup code demonstrates two child elements nested inside a parent element:
<family>
<member>Joe</member>
<member>Mary</member>
</family>
XML structures must be correctly nested. This means that each element must be closed in the correct place. The following sample code demonstrates incorrect nesting:
<family>
<member>
John
</family>
</member>
This code is not well-formed because the "member" element closes outside the "family" element instead of inside it.
Case
-
XML elements are case sensitive. This means that XML parsers, used within applications, interpret elements differently when different cases are involved. The following sample markup demonstrates two different opening element tags:
<family>
<Family>
These elements are not the same because the initial letters use different cases. Rather than including two elements with the same characters but different cases, a common error is to type an element tag incorrectly by using the wrong case, which can cause an application to fail. In XHTML, which is a form of XML, elements can only be lower case.
-