|
Reading a DOM tree from XML document |
|
|
DOM is a high-level API for processing XML data. DOM uses SAX to
analyze the source. The difference from SAX is that there is no
need to handle XML element directly. Entire document is composed
and returned by a DocumentBuilder instance.
Sample below shows ordinary loading of XML using DOM:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
/**
* This sample program shows how to load XML data
* using DOM interface.
*/
public class Test {
public static void main(String[] args) {
try {
// first of all we request out
// DOM-implementation:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// then we have to create document-loader:
DocumentBuilder loader = factory.newDocumentBuilder();
// loading a DOM-tree...
Document document = loader.parse("sample.xml");
// at last, we get a root element:
Element tree = document.getDocumentElement();
// ... do something with document element ...
} catch (IOException ex) {
// any IO errors occur:
handleError(ex);
} catch (SAXException ex) {
// parse errors occur:
handleError(ex);
} catch (ParserConfigurationException ex) {
// document-loader cannot be created which,
// satisfies the configuration requested
handleError(ex);
} catch (FactoryConfigurationError ex) {
// DOM-implementation is not available
// or cannot be instantiated:
handleError(ex);
}
}
private static final void handleError(Throwable ex) {
// ... handle error here...
}
}
|
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.