XML Syntax
Rules of the eXtensible Markup Language (XML)
-
All XML elements must have a closing tag
<p>This is a paragraph</p> -
Comments in XML
<!-- This is a comment --> -
XML tags are case sensitive
<TITLE>This example is incorrect</title> <!-- INCORRECT --> <title>This example is correct</title> -
XML elements must be properly nested
<strong><em>This text is important and emphasized</strong></em> <!-- INCORRECT because closing em tag appears out of order --> <strong><em>This text is important and emphasized</em></strong> -
XML documents must have a root element
XML documents must contain one element that is the parent of all other elements. This element is called the root element.
<html> <head> <title>Title</title> </head> </html> -
XML attribute values must be quoted
<img src=image.png/> <!-- INCORRECT because `image.png` is not quoted --> <img src="image.png"> -
Special characters in XML
<code>if salary < 1000:</code> <!-- INCORRECT because `<` confused with start of tag --> <code>if salary < 1000:</code>Entity Symbol Description < < less than > > greater than & & ampersand ' ’ apostrophe " ” quotation mark
Practice
Syntax
Identify the two XML errors in each of the following examples and correct them. (solutions)
<?xml version="1.0"?>
<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>Eric T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
-
Element names are case sensitive –
<Author>should be<author> -
Attribute values must be quoted –
category="WEB"
<?xml version="1.0"?>
<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>Eric T. Ray & John S. Green</author>
<year>2003</year>
<price>39.95</price>
</book>
-
XML documents must have a single root element
-
XML entities (i.e.,
&) must be escaped –&
<?xml version="1.0"?>
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005<month>August</year></month>
<price>29.99</price>
</bookstore>
-
XML tags must be closed – missing
</book>before</bookstore> -
XML tags must be nested correctly – close
yeartag beforemonth
Design
Design an XML document to track a triathlon race. Racers have a number, first name, last name, and race times for swimming, biking, and running.