Apache Xerces' weird error message

For one of my projects I’m using Apache’s Xerces C++ XML Parser and run into this strange error:

The primary document entity could not be opened.

Took me a while to figure out that Xerces simply wants to say “File not found” here, because I was was calling parse() with the data to be parsed, while Xerces expects a file name here. Silly me.

However: Here’s how to parse an XML string using Xerces SAX parser. You need to use a MemBufInputSource:

#define XNS XERCES_CPP_NAMESPACE_QUALIFIER 
std::string xmldoc("<first><second>Some Text</second></first>");
//

//  Create a SAX parser object.

//

XNS SAX2XMLReader* parser = 
	XNS XMLReaderFactory::createXMLReader();
//

//  Create the handler object and install it

//

YourContentHandler handler();
parser->setContentHandler(&handler);
parser->setErrorHandler(&handler);
XNS MemBufInputSource source(
	(const XMLByte*)xmldoc.c_str(),
	xmldoc.length(),
	"a name for the input source",
	false
);
parser->parse(source);

Published: April 04 2007