Attributes add extra information to an element. Instead of putting information into a subelement, you can use an attribute. In the XML community, deciding whether to use subelements or attributes—and what information should go into an attribute—is a matter of great debate, with no clear consensus. Here’s the SuperProProductList example with ID and Name attributes instead of ID and Name subelements:
<?xml version="1.0"?>
<SuperProProductList>
<Product ID="1" Name="Chair">
<Price>49.33</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="2" Name="Car">
<Price>43399.55</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="3" Name="Fresh Fruit Basket">
<Price>49.99</Price>
<Available>False</Available>
<Status>4</Status>
</Product>
</SuperProProductList>
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, <ProductName="Chair" /> is acceptable, but <Product Name=Chair /> or <Product Name /> isn’t. However, you do have one bit of flexibility—you can use single or double quotes around any attribute value. It’s convenient to use single quotes if you know the text value inside will contain a double quote (as in <Product Name='Red "Sizzle" Chair' />). If your text value has both single and double quotes, use double quotes around the value and replace the double quotes inside the value with the " entity equivalent.
No comments:
Write comments