How to use XML attributes

If you know basic principles from the article How to create a XML document, you can use attributes to add extra information to an element. Instead of putting information into a sub-element, you can use an attribute. In the XML community, deciding whether to use sub-elements or attributes—and what information should go into an attribute—is a matter of great debate, with no clear consensus. The next example shows usage of attributes in a XML document.

 

<?xml version=”1.0″?>

<BooksList>

<Book ISBN-13=” 978-0545139700” Title = “Harry Potter and the Deathly Hallows“>

<Author>J.K. Rowling</Author>

<Price>14.99</Price>

<Available>True</Available>

</Book>

<Book ISBN-13=”978-1451648539” Title=”Steve Jobs”>

<Author>Walter Isaacson</Author>

<Price>17.88</Price>

<Available>True</Available>

</Book>

<Book ISBN-13=”978-0765309761” Title=”Tunnel Vision”>

<Author>Gary Braver</Author>

<Price>17.15</Price>

<Available>False</Available>

</Book>

</BooksList>

 

Using attributes in XML is more stringent than in HTML. In XML, attributes must always have values, and these values must use quotation marks. For example, <Product Name=”Car” /> is acceptable, but <Product Name=Car /> or <Product Name /> isn’t.