Programming with DOM

| Questions |
| Concurrent access Creating a DOM Parser with JAXP and DOM Level 3 Serializing a DOM document Java Object Serialization of a DOM Specifying non-Xerces DOM implementation Accessing the DOM Level 3 API Using DOM Level 3 with JDK 1.4 and higher XML Schema API and DOM Revalidation of DOM document in Memory Handling Errors in DOM Controlling Entity Representation Associating user data with a Node Making getElementById work Setting ID attribute Accessing type information
| Answers |
| Is Xerces DOM implementation thread-safe? |
| No. DOM does not require implementations to be thread safe. If you need to access the DOM from multiple threads, you are required to add the appropriate locks to your application code.
| How do I create a DOM parser? |
| You can create a DOM parser by using the Java APIs for XML Processing (JAXP) or using the DOM Level 3 Load and Save. The following source code shows how to create the parser with JAXP:
    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.w3c.dom.Document;
    import org.xml.sax.SAXException;

    ...

    String xmlFile = "file:///xerces-2_9_1/data/personal.xml";
    try {
        DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlFile);
    }
    catch (FactoryConfigurationError e) {
        // unable to get a document builder factory
    }
    catch (ParserConfigurationException e) {
        // parser was unable to be configured
    catch (SAXException e) {
        // parsing error
    }
    catch (IOException e) {
        // i/o error
    }
The following source code shows how to create the parser using DOM Level 3:
    import  org.w3c.dom.bootstrap.DOMImplementationRegistry;
    import  org.w3c.dom.Document;
    import  org.w3c.dom.ls.DOMImplementationLS;
    import  org.w3c.dom.ls.LSParser;

    ...

    DOMImplementationRegistry registry =
        DOMImplementationRegistry.newInstance();

    DOMImplementationLS impl =
        (DOMImplementationLS)registry.getDOMImplementation("LS");

    LSParser builder = impl.createLSParser(
        DOMImplementationLS.MODE_SYNCHRONOUS, null);

    Document document = builder.parseURI("data/personal.xml");
| You can now use DOM Level 3 Load/Save and Core interfaces with the regular Xerces distribution.
| How do I serialize DOM to an output stream? |
| You can serialize a DOM tree by using the DOM Level 3 Load and Save. `LSSerializer` performs automatic namespace fixup to make your document namespace well-formed.
    import  org.w3c.dom.bootstrap.DOMImplementationRegistry;
    import  org.w3c.dom.Document;
    import  org.w3c.dom.ls.DOMImplementationLS;
    import  org.w3c.dom.ls.LSSerializer;

    ...

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

    DOMImplementationLS impl =
        (DOMImplementationLS)registry.getDOMImplementation("LS");

    ...

    LSSerializer writer = impl.createLSSerializer();
    String str = writer.writeToString(document);
You can also serialize a DOM tree by using the JAXP Transformer API. It is also possible to serialize a DOM tree by using the Xerces `org.apache.xml.XMLSerializer` serialization code directly. This non-standard way of serializing a DOM has been deprecated since Xerces-J 2.9.0 and should be avoided if possible.
    import org.apache.xml.serialize.OutputFormat;
    import org.apache.xml.serialize.XMLSerializer;
    import org.apache.xml.serialize.LineSeparator;

    ...

    OutputFormat format = new OutputFormat((Document)core);
    format.setLineSeparator(LineSeparator.Windows);
    format.setIndenting(true);
    format.setLineWidth(0);
    format.setPreserveSpace(true);
    XMLSerializer serializer = new XMLSerializer (
        new FileOutputStream("output.xml"), format);
    serializer.asDOMSerializer();
    serializer.serialize(document);
| Does Xerces DOM implement java.io.Serializable? |
| Yes. Xerces DOM can be serialized using Java object serialization. It is recommended that a DOM be serialized as XML where possible instead of using object serialization. By choosing object serialization you sacrifice interoperability between parsers and we do not guarantee interoperability between versions of Xerces. It should be used with caution. Some rough measurements have shown that XML serialization performs better than Java object serialization and that XML instance documents require less storage space than object serialized DOMs.
| How do I supply my own implementation of the DOM? |
| Use the http://apache.org/xml/properties/dom/document-class-name property to register your own implementation of the `org.w3c.dom.Document` interface. Xerces provides the following implementations of the `org.w3c.dom.Document` interface: `org.apache.xerces.dom.CoreDocumentImpl` -- supports DOM Level 3 Core Recommendation. `org.apache.xerces.dom.DocumentImpl` -- supports DOM Level 3 Core, Mutation Events, Traversal and Ranges. `org.apache.xerces.dom.PSVIDocumentImpl` -- provides access to the post schema validation infoset via DOM.
| How do I access the DOM Level 3 functionality? |
| The DOM Level 3 functionality is now exposed by default since Xerces-J 2.7.0. The experimental interfaces which were once present in the `org.apache.xerces.dom3` package no longer exist. This package existed primarily so that the DOM Level 2 and DOM Level 3 implementations in Xerces-J 2.6.2 and prior could co-exist. Code which depended on the `org.apache.xerces.dom3` package must be modified to use the official DOM Level 3 API located in the `org.w3c.dom.*` packages. For more information, refer to the DOM Level 3 Implementation page.
| How do I run DOM Level 3 applications under JDK 1.4 and higher? |
| Use the Endorsed Standards Override Mechanism to specify xercesImpl.jar and xml-apis.jar. A more complete description is available here.
| How do I retrieve PSVI from the DOM? |
| By default Xerces does not store the PSVI information in the DOM tree. The following source shows you how to parse an XML document (using JAXP) and how to retrieve PSVI (using the XML Schema API):
    //dbf is JAXP DocumentBuilderFactory

    // all of the following features must be set:
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute("http://apache.org/xml/features/validation/schema",
        Boolean.TRUE);

    // you also must specify Xerces PSVI DOM implementation
    // "org.apache.xerces.dom.PSVIDocumentImpl"
    dbf.setAttribute("http://apache.org/xml/properties/dom/document-class-name",
        "org.apache.xerces.dom.PSVIDocumentImpl");

    ...
    Document doc = db.parse(args[0]);
    if (doc.getDocumentElement().isSupported("psvi", "1.0")){
        ElementPSVI psviElem = (ElementPSVI)doc.getDocumentElement();
        XSElementDeclaration decl = psviElem.getElementDeclaration();
        ...
    }
If you want to build the DOM tree in memory and be able to access the PSVI information you need to start by instantiating org.apache.xerces.dom.PSVIDocumentImpl or you need to use the DOM Level 3 API as shown in the following example:
    System.setProperty(DOMImplementationRegistry.PROPERTY,
        "org.apache.xerces.dom.DOMXSImplementationSourceImpl");

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

    DOMImplementation impl =
        (DOMImplementation) registry.getDOMImplementation("psvi");
The PSVI information will not be added or modified as you modify the tree in memory. Instead, if you want to get updated PSVI information, you need to validate your DOM in memory using the normalizeDocument method as described in the next question. You can find more information about how to use the XML Schema API here.
| How can I make sure that my DOM document in memory conforms to a schema? |
| DOM revalidation is supported via W3C DOM Level 3 Core Document.normalizeDocument().
| This release only supports revalidation against XML Schemas and DTDs. Revalidation against other schema types is not implemented.
To revalidate the document you need: Create the DOMParser. Retrieve `DOMConfiguration` from the `Document`, and set validate feature to true. Provide XML Schemas (agains which validation should occur) by either setting xsi:schemaLocation / xsi:noSchemaLocation attributes on the `documentElement`, or by setting `schema-location` parameter on the `DOMConfiguration`. Relative URIs for the schema documents will be resolved relative to the documentURI (which should be set). Otherwise, you can implement your own `LSResourceResolver` and set it via `resource-resolver` on the `DOMConfiguration`. Note: if a document contains any DOM Level 1 nodes (the nodes created using createElement, createAttribute, etc.) a fatal error will occur as described in the Namespace Normalization algorithm. In general, the DOM specification discourages using DOM Level 1 nodes in the namespace aware application: DOM Level 1 methods are namespace ignorant. Therefore, while it is safe to use these methods when not dealing with namespaces, using them and the new ones at the same time should be avoided. DOM Level 1 methods solely identify attribute nodes by their nodeName. On the contrary, the DOM Level 2 methods related to namespaces, identify attribute nodes by their namespaceURI and localName. Because of this fundamental difference, mixing both sets of methods can lead to unpredictable results.
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMConfiguration;
    import org.w3c.dom.ls.LSParser;

    .....

    Document document = builder.parseURI("data/personal-schema.xml");
    DOMConfiguration config = document.getDomConfig();
    config.setParameter("error-handler",new MyErrorHandler());
    config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
    config.setParameter("validate", Boolean.TRUE);
    document.normalizeDocument();
For more information, please refer to the DOM Level 3 Implementation page.
| How do I handle errors? |
| You should register an error handler with the parser by supplying a class which implements the `org.xml.sax.ErrorHandler` interface. This is true regardless of whether your parser is a DOM based or SAX based parser. You can register an error handler on a `DocumentBuilder` created using JAXP like this:
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;

    ErrorHandler handler = new ErrorHandler() {
        public void warning(SAXParseException e) throws SAXException {
            System.err.println("[warning] "+e.getMessage());
        }
        public void error(SAXParseException e) throws SAXException {
            System.err.println("[error] "+e.getMessage());
        }
        public void fatalError(SAXParseException e) throws SAXException {
            System.err.println("[fatal error] "+e.getMessage());
            throw e;
        }
    };

    DocumentBuilder builder = /* builder instance */;
    builder.setErrorHandler(handler);
If you are using DOM Level 3 you can register an error handler with the `LSParser` by supplying a class which implements the `org.w3c.dom.DOMErrorHandler` interface. Note: all exceptions during parsing or saving XML data are reported via DOMErrorHandler.
| How can I control the way that entities are represented in the DOM? |
| The Xerces `http://apache.org/xml/features/dom/create-entity-ref-nodes` feature (or corresponding DOM Level 3 LSParser `entities` feature) controls how entities appear in the DOM tree. When one of those features is set to true (the default), an occurrence of an entity reference in the XML document will be represented by a subtree with an EntityReference node at the root whose children represent the entity expansion. If the feature is false, an entity reference in the XML document is represented by only the nodes that represent the entity expansion. In either case, the entity expansion will be a DOM tree representing the structure of the entity expansion, not a text node containing the entity expansion as text.
| How do I associate my own data with a node in the DOM tree? |
| The class `org.apache.xerces.dom.NodeImpl` provides the `setUserData(Object o)` and the `Object getUserData()` methods that you can use to attach any object to a node in the DOM tree. Beware that you should try and remove references to your data on nodes you no longer use (by calling `setUserData(null)`, or these nodes will not be garbage collected until the entire document is garbage collected. If you are using Xerces with the DOM Level 3 support you can use `org.w3c.dom.Node.setUserData()` and register your own `UserDataHandler`.
| Why does getElementById not work for documents validated against XML Schemas? |
| Make sure the validation feature and the schema feature are turned on before you parse a document.
| How do I specify an ID attribute in the DOM? |
| You can use the DOM level 3 setIdAttribute, setIdAttributeNS, and setIdAttributeNode methods to specify ID attribute in the DOM. See DOM Level 3.
| How do I access type information in the DOM? |
| DOM Level 3 defines a TypeInfo interface that exposes type information for element and attribute nodes. The type information depends on the document schema and is only available if Xerces was able to find the corresponding grammar (DOM Level 3 `validate` or `validate-if-schema` feature must be turned on). If you need to access the full PSVI in the DOM please refer to Using XML Schemas.

Copyright © 1999-2007 The Apache Software Foundation. All Rights Reserved.