Parsing XML file containing HTML entities in Java without changing the XML
<p>I have to parse a bunch of XML files in Java that sometimes -- and invalidly -- contain HTML entities such as <code>&amp;mdash;</code>, <code>&amp;gt;</code> and so forth. I understand the correct way of dealing with this is to add suitable entity declarations to the XML file before parsing. However, I can't do that as I have no control over those XML files.</p>

<p>Is there some kind of callback I can override that is invoked whenever the Java XML parser encounters such an entity? I haven't been able to find one in the API.</p>

<p>I'd like to use:</p>

<pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder parser = dbf.newDocumentBuilder();
Document        doc    = parser.parse( stream );
</code></pre>

<p>I found that I can override <code>resolveEntity</code> in <code>org.xml.sax.helpers.DefaultHandler</code>, but how do I use this with the higher-level API?</p>

<p>Here's a full example:</p>

<pre><code>public class Main {
    public static void main( String [] args ) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = dbf.newDocumentBuilder();
        Document        doc    = parser.parse( new FileInputStream( "test.xml" ));
    }
</code></pre>

<p>}</p>

<p>with test.xml:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;foo&gt;
    &lt;bar&gt;Some&amp;nbsp;text &amp;mdash; invalid!&lt;/bar&gt;
&lt;/foo&gt;
</code></pre>

<p>Produces:</p>

<pre><code>[Fatal Error] :3:20: The entity "nbsp" was referenced, but not declared.
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 20; The entity "nbsp" was referenced, but not declared.
</code></pre>

<p>Update: I have been poking around in the JDK source code with a debugger, and boy, what an amount of spaghetti. I have no idea what the design is there, or whether there is one. Just how many layers of an onion can one layer on top of each other?</p>

<p>They key class seems to be <code>com.sun.org.apache.xerces.internal.impl.XMLEntityManager</code>, but I cannot find any code that either lets me add stuff into it before it gets used, or that attempts to resolve entities without going through that class.</p>