Besides collection of child elements each XML-item may contain any set of attributes. Each attribute is a name-value pair. XML attributes should be located inside the openning mark-up of the element, just between element-name and '>' symbol. The usage of attributes may lead the element to be empty, e.g has no children. XML-document below is utilizing attributes.


Attribute are convenient when it is necessary to set some primitive (non-complex) value.

<purchase-order date="2005-10-31" number="12345">

<!-- file: sample.xml -->
<?xml version="1.0"?>


<purchased-by name="My name"> <!-- since address may be too complex for attribute value, we place it to a dedicated element --> <address>My address</address> </purchased-by> <order-items> <!-- here is an example of empty element i.e. containing no nested elements --> <item code="687" type="CD" label="Some music" /> <item code="129851" type="DVD" label="Some video"/> </order-items> </purchase-order>

Parent Category: Java SE Tips