Rules of the eXtensible Markup Language (XML)

  1. All XML elements must have a closing tag

    <p>This is a paragraph</p>
    
  2. Comments in XML

    <!-- This is a comment -->
    
  3. XML tags are case sensitive

    <TITLE>This example is incorrect</title>  <!-- INCORRECT -->
    
    <title>This example is correct</title>
    
  4. 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>
    
  5. 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>
    
  6. XML attribute values must be quoted

    <img src=image.png/> <!-- INCORRECT because `image.png` is not quoted -->
    
    <img src="image.png">
    
  7. Special characters in XML

    <code>if salary < 1000:</code> <!-- INCORRECT because `<` confused with
                                        start of tag -->
    
    <code>if salary &lt; 1000:</code>
    
    Entity Symbol Description
    &lt; < less than
    &gt; > greater than
    &amp; & ampersand
    &apos; apostrophe
    &quot; 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>
  1. Element names are case sensitive – <Author> should be <author>

  2. 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>
  1. XML documents must have a single root element

  2. XML entities (i.e., &) must be escaped – &amp;

<?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>
  1. XML tags must be closed – missing </book> before </bookstore>

  2. XML tags must be nested correctly – close year tag before month

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.