Use Elements Sparingly, Attributes Excessively
After giving you two recommendations about organization, I will now make what might seem like a counterintuitive suggestion: use elements infrequently and, instead, use attributes whenever possible.
To get a better idea of what I’m talking about, take a look at the XML fragment in Example 5-3.
<person> <firstName>Adam</firstName> <lastName>Duritz</lastName> <address type="home"> <street>102 Elizabeth Lane</street> <street>Apartment 23</street> <city>Los Angeles</city> <state>California</state> <zipCode>92013</zipCode> </address> </person>
To optimize this XML, you should try and convert as much as possible
into attributes. The rule of thumb here is that any single-valued
content can be turned into an attribute, while multivalued content
must stay as elements. So, the firstName
and
lastName
elements can be converted into
attributes; each will always have only one value. Hence, the XML can
be modified to look as follows:
<person firstName="Adam" lastName="Duritz">
<address type="home">
<street>102 Elizabeth Lane</street>
<street>Apartment 23</street>
<city>Los Angeles</city>
<state>California</state>
<zipCode>92013</zipCode>
</address>
</person>
The address
element could not be converted to an attribute. First, it has its own content, and second, there could be multiple addresses for the same person (a home address, work address, and so forth). Within that element, you can perform the same ...
Get Java Enterprise Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.