Attributes [XML Standards]
Attributes allow you to add information about an element using name-value pairs. Attributes are often used to define properties of elements that are not considered the content of the element, though in some cases (for example, the HTML
img element) the content of the element is determined by attribute values.
Attributes can appear in start or empty tags, but not in end tags. The syntax looks like:
<elementName att1Name="att1Value" att2Name="att2Value"...>
<elementName att1Name="att1Value" att2Name="att2Value".../>
Attributes must have both a name and a value. No names without values are permitted. An element cannot have two attributes with the same name. Because the order in which attributes appeared inside of an element is not considered important by XML, it might not be preserved by the XML parser.
Like element names, attribute names are case-sensitive and must start with a letter or underscore. The rest of the name can contain letters, digits, hyphens, underscores, and periods.
Colons are reserved for use with namespaces. For more information about which Unicode characters are acceptable letters and digits, see Appendix B of the XML specification.
Attribute values must follow the same rules as normal textual content, with a few additional restrictions. Attribute values can contain only text, not element markup. Entity references and character references are allowed within attribute values, but CDATA sections are not.
Finally, quotes might have to be escaped. The XML specification allows you to use either single or double quotes to indicate attributes, though the type of quote used must be the same on both sides of the attribute value. You must use quotes around attribute values, however. XML parsers will simply reject documents that do not use quotes around attribute values and report an error.
If you use single quotes to indicate an attribute value, you must represent single quotes inside the attribute value using the
' entity reference.
<myElement contraction='isn't' />
If you use double quotes to indicate an attribute value, you must represent double quotes inside the attribute value using the
" entity reference.
<myElement question="They asked "Why?"" />
You can, however, use double quotes inside of single-quoted attribute values and vice-versa, as the following examples demonstrate.
<myElement contraction="isn't" /> <myElement question='They asked "Why?"' />
You can also use different types of quotes on different attribute values within the same element.
<myElement contraction="isn't" question='They asked "Why?"' />
XML parsers do not preserve white space within attribute values the same way that they preserve white space within element textual content. In a validating parser with access to a DTD, all white space within an attribute value of any type other than CDATA is replaced with a single space; starting and ending white space will be stripped.