The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.xml.parsers  [8 examples] > DOM Parsing Options  [3 examples]

e516. Preventing Expansion of Entity References While Parsing an XML File

By default, entity references are expanded during parsing. This example demonstrates how to leave the entity references in the DOM document

Note: The default parser in J2SE 1.4 expands entity references in attribute values. There is no way to prevent this.

    // Parses an XML file without expanding entity references and returns
    // a DOM document. If validating is true, the contents is validated
    // against the DTD specified in the file.
    public static Document parseXmlFileNoExpandER(String filename, boolean validating) {
        try {
            // Create a builder factory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validating);
    
            // Prevent expansion of entity references
            factory.setExpandEntityReferences(false);
    
            // Create the builder and parse the file
            Document doc = factory.newDocumentBuilder().parse(new File(filename));
            return doc;
        } catch (SAXException e) {
            // A parsing error occurred; the xml input is not valid
        } catch (ParserConfigurationException e) {
        } catch (IOException e) {
        }
        return null;
    }

 Related Examples
e514. Converting CDATA Nodes into Text Nodes While Parsing an XML File
e515. Ignoring Comments While Parsing an XML File

See also: DOM    SAX   


© 2002 Addison-Wesley.