diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index f3db3f0..94ad656 100644
*** a/src/backend/utils/adt/xml.c
--- b/src/backend/utils/adt/xml.c
*************** PgXmlErrorContext *
*** 928,933 ****
--- 928,934 ----
  pg_xml_init(PgXmlStrictness strictness)
  {
  	PgXmlErrorContext *errcxt;
+ 	void	   *cur_errcxt;
  
  	/* Do one-time setup if needed */
  	pg_xml_init_library();
*************** pg_xml_init(PgXmlStrictness strictness)
*** 956,961 ****
--- 957,991 ----
  
  	xmlSetStructuredErrorFunc((void *) errcxt, xml_errorHandler);
  
+ 	/*
+ 	 * Verify that we're able to read back the error context we just set.
+ 	 * If this fails, the error context we saved above is probably equally
+ 	 * bogus, and since that leave us without a way to restore the context
+ 	 * in pg_xml_done(), we complain early and loudly. The only known
+ 	 * situation in which we fail this test is if we compile with headers
+ 	 * from a libxml2 which doesn't track the structured error context
+ 	 * separately (<= 2.7.3), but (dynamically) link a version that does.
+ 	 */
+ 
+ #ifdef HAVE_XMLSTRUCTUREDERRORCONTEXT
+ 	cur_errcxt = xmlStructuredErrorContext;
+ #else
+ 	cur_errcxt = xmlGenericErrorContext;
+ #endif
+ 	if (cur_errcxt != (void *) errcxt)
+ 	{
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED)
+ 				,errmsg("could not setup XML error handler")
+ 				,errdetail("libxml2 error context could not be queried")
+ #ifndef HAVE_XMLSTRUCTUREDERRORCONTEXT
+ 				,errhint("Postgres was built with a libxml version without "
+ 						 "xmlStructuredErrorContext but is probably now using "
+ 						 "a version with it. This situation is unsupported")
+ #endif
+ 		));
+ 	}
+ 
  	return errcxt;
  }
  
*************** xml_errorHandler(void *data, xmlErrorPtr
*** 1494,1502 ****
  	int			level = error->level;
  	StringInfo	errorBuf;
  
! 	/* Defend against someone passing us a bogus context struct */
  	if (xmlerrcxt->magic != ERRCXT_MAGIC)
! 		elog(ERROR, "xml_errorHandler called with invalid PgXmlErrorContext");
  
  	/*----------
  	 * Older libxml versions report some errors differently.
--- 1524,1536 ----
  	int			level = error->level;
  	StringInfo	errorBuf;
  
! 	/*
! 	 * Defend against someone passing us a bogus context struct.
! 	 * We force a backend exit if this check fails because longjmp()ing
! 	 * out of libxml might render it unuseable.
! 	 */
  	if (xmlerrcxt->magic != ERRCXT_MAGIC)
! 		elog(FATAL, "xml_errorHandler called with invalid PgXmlErrorContext");
  
  	/*----------
  	 * Older libxml versions report some errors differently.
