XML elements can contain attributes, similar to HTML, in the start tag.
Attributes provide additional information about the element.
XML attribute
From the HTML, you will recall this: . The SRC attribute provides additional information about the element.
In HTML (and in XML), properties provide additional information about the element:
<a href="demo.asp">
Properties usually provide information that is not part of the data. In the following example, the file type has nothing to do with the data, but it is important for the software that needs to handle the element:
<file type="gif">computer.gif</file>
XML attribute must be quoted
Property values must be surrounded by quotes, but single and double quotes are available. For example, a person's sex tag can be written like this:
<person sex="female">
Or this can also be:
<person sex='female'>
Note: If the property value itself contains double quotes, it is necessary to surround it with single quotes, like this example:
<gangster name='George "Shotgun" Ziegler'>
Or you can use entity references:
<gangster name="George "Shotgun" Ziegler">
XML element vs. property
Take a look at these examples:<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example, sex is an attribute. In the second example, sex is a child element. All two examples can provide the same information.
There is no rule that tells us when to use attributes and when to use child elements. My experience is that in HTML, attributes are convenient to use, but in XML you should try to avoid using attributes. If the information feels like data, use a child element.
The way I like it the most
The following three XML documents contain exactly the same information:
The date attribute is used in the first example:<note date="08/08/2008">
<to>George</to>
<from>John</from>
<body>Don't forget the meeting this weekend!</body>
</note>
The second example uses the date element:<note>
<date>08/08/2008</date>
<to>George</to>
<from>John</from>
<body>Don't forget the meeting this weekend!</body>
</note>
The third example uses the extended date element (which is my favorite):<note>
<date>
<day>08</day>
<month>08</month>
<year>2008</year>
</date>
<to>George</to>
<from>John</from>
<body>Don't forget the meeting this weekend!</body>
</note>