|
Using XML locator to indicate current parser position |
|
|
Often when SAX-parser meets bad symbol in source XML-document
it reports about this error. For the user it will be great to
know the line and column numbers where the error occurred.
SAX tracks current reading position in source XML using locator.
SAX-handler can save that locator for the following detailed
error output.
The code below shows how to handle the locator:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* This example demonstrates how to indicate current position
* in the source XML-document.
*/
public class SampleOfXmlLocator extends DefaultHandler {
private Locator locator;
// this will be called when XML-parser starts reading
// XML-data; here we save reference to current position in XML:
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
// here we accept only 'purchase-order';
// in all the rest cases we will raise
// an exception with detailed message:
public void startElement(String uri, String localName,
String qName, Attributes attrs) throws SAXException {
if (qName.equals("purchase-order")) {
// ... here process element start:
} else {
// compose a text with location of error-case:
String location = "";
if (locator != null) {
location = locator.getSystemId(); // XML-document name;
location += " line " + locator.getLineNumber();
location += ", column " + locator.getColumnNumber();
location += ": ";
}
throw new SAXException(location + "Illegal element");
}
}
/**
* Application entry point
* @param args command-line arguments
*/
public static void main(String[] args) {
try {
// creates and returns new instance of SAX-implementation:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
// create SAX-parser...
SAXParser parser = factory.newSAXParser();
// and parse:
parser.parse("sample.xml", new SampleOfXmlLocator());
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.