How do you read an XML document using the SAX parser in Java?
A) By implementing the
ContentHandler
interfaceB) By extending the
DOMParser
classC) By using the
JAXBContext
classD) By parsing the XML as a string
Answer:
A) By implementing the
ContentHandler
interfaceExplanation:
To read an XML document using the SAX parser in Java, you implement the ContentHandler
interface. This interface defines methods for handling events such as the start and end of elements, processing character data, and handling namespaces. The SAX parser triggers these events as it reads through the XML document sequentially.
For example:
public class MyContentHandler implements ContentHandler {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// Handle the start of an element
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// Handle the end of an element
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// Handle character data
}
// Other methods...
}
In this example, the startElement()
and endElement()
methods handle the start and end of elements, while the characters()
method processes character data.