diff --git a/src/xercesc/parsers/AbstractDOMParser.cpp b/src/xercesc/parsers/AbstractDOMParser.cpp
index 7b4129343104c292bd192b6672b47a502eb7824d..7a9c25b790db78db2941f45968e46783b4349239 100644
--- a/src/xercesc/parsers/AbstractDOMParser.cpp
+++ b/src/xercesc/parsers/AbstractDOMParser.cpp
@@ -24,8 +24,6 @@
 *
 */
 
-
-
 // ---------------------------------------------------------------------------
 //  Includes
 // ---------------------------------------------------------------------------
@@ -853,6 +851,15 @@ void AbstractDOMParser::endEntityReference(const XMLEntityDecl&)
     fCurrentNode   = fCurrentParent;
     fCurrentParent = fCurrentNode->getParentNode ();
 
+    // When the document is invalid but we continue parsing, we may
+    // end up seeing more 'end' events than the 'start' ones.
+    //
+    if (fCurrentParent == 0 && fDocument != 0)
+    {
+      fCurrentNode = fDocument->getDocumentElement ();
+      fCurrentParent = fCurrentNode;
+    }
+
     if (erImpl)
         erImpl->setReadOnly(true, true);
 }
@@ -866,6 +873,15 @@ void AbstractDOMParser::endElement( const   XMLElementDecl&
     fCurrentNode   = fCurrentParent;
     fCurrentParent = fCurrentNode->getParentNode ();
 
+    // When the document is invalid but we continue parsing, we may
+    // end up seeing more 'end' events than the 'start' ones.
+    //
+    if (fCurrentParent == 0 && fDocument != 0)
+    {
+      fCurrentNode = fDocument->getDocumentElement ();
+      fCurrentParent = fCurrentNode;
+    }
+
     // If we've hit the end of content, clear the flag.
     //
     if (fCurrentParent == fDocument)