Flexibility
XML is a very flexible standard. However, in practice, XML applications are only as flexible as you, the programmer, make them. In this section, we will look at some tips to ensure your applications exploit XML flexibility.
Building for Flexibility
The BestDeal application puts very few constraints on the structure of the XML document. Add elements in the XML document and they are simply ignored. For example, BestDeal would accept the following vendor element:
<xbe:vendor> <xbe:name>Playfield Training</xbe:name> <xbe:contact>John Doe</xbe:contact> <xbe:price-quote delivery="5">999.00</xbe:price-quote> <xbe:price-quote delivery="15">899.00</xbe:price-quote> </xbe:vendor>
but ignores the contact information. In general, it's a good idea to simply ignore unknown elementsas HTML browsers have always done.
Enforce a Structure
However it's not difficult to validate their structure from the event handler. The following code snippet (adapted from startElement()) checks the structure and throws a SAXException if a vendor element contains anything but name or price elements.
case VENDOR: if(name.equals("name")) { state = VENDOR_NAME; buffer = new StringBuffer(); } else if(name.equals("price-quote")) { state = VENDOR_PRICE_QUOTE; String st = attributes.getValue("","delivery"); delivery = Integer.parseInt(st); buffer = new StringBuffer(); } else throw new SAXException("Expecting <xbe:name> or <xbe:price-quote>"); break;
Given the listing with a contact element, it reports that
org.xml.sax.SAXException: Expecting <xbe:name> or <xbe:price-quote>
However, in practice, if your application is really dependent on the structure of the document, it is best to write a schema and use a validating parser.
What's Next
In the previous chapter and in this chapter, you learned how to read XML documents. In the next chapter, you learn how to write documents, thereby closing the loop.