Sunday, October 3, 2010

XML Attributes

From HTML you will remember this: < IMG SRC="comp.gif" >. The SRC attribute provides additional information about the IMG element. In HTML (and in XML) attributes provide additional information about elements:

< img src="computer.gif" >
< a href="demo.asp" >

Attributes often provide information that is not a part of the data. In the example below, the file type is irrelevant to the data, but important to the software that wants to manipulate the element:

< file type="gif" > computer.gif < /file >
Students now u know abt basic XML, its scripting rules. Lets understand XML attributes which can be understood as property of an element.

Here are simple rules for XML elements

Quote Styles, "female" or 'female'?
Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag can be written like this:

< person sex="female" > or like this:
< person sex='female' >

Note: If the attribute value itself contains double quotes it is necessary to use single quotes, like in this example:

< Inspector name='George "Rain" Abslum' >

Note: If the attribute value itself contains single quotes it is necessary to use double quotes, like in this example:

< Inspector name="George 'Rain' Abslum" >

Use of Elements vs. Attributes: Data can be stored in child elements or in attributes.

E.g. Take a look at these examples:

< 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 last, sex is a child element. Both examples provide the same information. There are no rules about when to use attributes, and when to use child elements. My experience is that attributes are handy in HTML, but in XML you should try to avoid them. Use child elements if the information feels like data.

E.g.Storing data in child elements.

The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
< note date="12/11/2002" >
< to > Tove < /to >
< from>Jani < /from >
< heading>Reminder < /heading >
< body>Don't forget me this weekend! < /body >
< /note >

A date element is used in the second example:

< note >
< date > 12/11/2002 < /date >
< to > Tove < /to >
< from>JaniReminder < /heading >
< body>Don't forget me this weekend! < /body >
< /note >
An expanded date element is used in the third: (THIS IS MY FAVORITE):

< note >
< date >
< day > 12 < /day >
< month > 11 < /month >
< year > 2002 </year >
< /date >
< to > Tove < /to >
< from > Jani < /from >
< heading > Reminder < /heading >
< body >Don't forget me this weekend! < /body >
< /note >

No comments:

Post a Comment