XML Attributes
Home ] Up ] The Document Prolog ] XML Elements ] The Root Element ] [ XML Attributes ] Attribute vs. Element? ] Whitespace and Comments ] XML Character Entities ] CDATA Sections ] Processing Instructions ] Well-Formed Documents ]

 

 

Sometimes an element doesn't provide all the necessary information about the contents of the element.  For example, consider the following XML:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <title>The World is Flat</title>
  <subtitle>A Brief History of the Twenty-First Century</subtitle>
  <author>Thomas Friedman</author>
  <publisher>Farrar, Straus and Giroux</publisher>
  <date-published>April 30, 2006</date-published>
  <isbn>0374292795</isbn>
  <pages>593</pages>
  <price>30.00</price>
</book>

Notice that we know the price of the book, but we don't know whether the price is in dollars, pounds, Euros, or rupees.  We also don't know whether it's a full retail price, or a discounted price.

We could solve the problem by adding more elements:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <title>The World is Flat</title>
  <subtitle>A Brief History of the Twenty-First Century</subtitle>
  <author>Thomas Friedman</author>
  <publisher>Farrar, Straus and Giroux</publisher>
  <date-published>April 30, 2006</date-published>
  <isbn>0374292795</isbn>
  <pages>593</pages>
  <price>30.00
    <currency>usd</currency>
    <type>full retail</type>
  </price>
</book>

However, if we have values in the form of a name/value pair, we have the option of using attributes:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <title>The World is Flat</title>
  <subtitle>A Brief History of the Twenty-First Century</subtitle>
  <author>Thomas Friedman</author>
  <publisher>Farrar, Straus and Giroux</publisher>
  <date-published>April 30, 2006</date-published>
  <isbn>0374292795</isbn>
  <pages>593</pages>
  <price currency="usd" type="full retail">30.00</price>
</book>

Attribute values must be enclosed within quotes.  That is, within matched pairs of:

  • double quotes, or 
  • single quotes (apostrophes)

Within an element, an attribute name may not be repeated.  For example:

<book title="The Elements of Style"
      author="William Strunk Jr."
      author="E. B. White"
/>

is incorrect, because the author attribute is repeated within the book element.

Instead, we could have:

<book>
  <title>The Elements of Style</title>
  <author>William Strunk Jr.</author>
  <author>E. B. White</author>
</book>

which is fine, because repetition of elements is allowed.

 
The page was last updated February 19, 2008