Interview Questions

How do I use XML namespaces with SAX 1.0?

XML Interview Questions and Answers


(Continued from previous question...)

101. How do I use XML namespaces with SAX 1.0?

The easiest way to use XML namespaces with SAX 1.0 is to use John Cowan's Namespace SAX Filter (see http://www.ccil.org/~cowan/XML). This is a SAX filter that keeps track of XML namespace declarations, parses qualified names, and returns element type and attribute names as universal names in the form:
URI^local-name
For example:
http://www.google.com/ito/sales^SalesOrder
Your application can then base its processing on these longer names. For example, the code:
public void startElement(String elementName, AttributeList attrs)
throws SAXException
{
...
if (elementName.equals("SalesOrder"))
{
// Add new database record.
}
...
}
might become:
public void startElement(String elementName, AttributeList attrs)
throws SAXException
{
...
if (elementName.equals("http://www.google.com/sales^SalesOrder"))
{
// Add new database record.
}
...
}
or:
public void startElement(String elementName, AttributeList attrs)
throws SAXException
{
...
// getURI() and getLocalName() are utility functions
// to parse universal names.
if (getURI(elementName).equals("http://www.foo.com/ito/sales"))
{
if (getLocalName(elementName).equals("SalesOrder"))
{
// Add new database record.
}
}
...
}
If you do not want to use the Namespace SAX Filter, then you will need to do the following in addition to identifying element types and attributes by their universal names:
* In startElement, scan the attributes for XML namespace declarations before doing any other processing. You will need to maintain a table of current prefix-to-URI mappings (including a null prefix for the default XML namespace).
* In startElement and endElement, check whether the element type name includes a prefix. If so, use your mappings to map this prefix to a URI. Depending on how your software works, you might also check if the local part of the qualified name includes any colons, which are illegal.
* In startElement, check whether attribute names include a prefix. If so, process as in the previous point.

(Continued on next question...)

Other Interview Questions