-->

Making Xerces parse a string instead of a file

2019-01-22 20:58发布

问题:

I know how to create a complete dom from an xml file just using XercesDOMParser:

xercesc::XercesDOMParser parser = new xercesc::XercesDOMParser();
parser->parse(path_to_my_file);
parser->getDocument(); // From here on I can access all nodes and do whatever i want

Well, that works... but what if I'd want to parse a string? Something like

std::string myxml = "<root>...</root>";
xercesc::XercesDOMParser parser = new xercesc::XercesDOMParser();
parser->parse(myxml);
parser->getDocument(); // From here on I can access all nodes and do whatever i want

I'm using version 3. Looking inside the AbstractDOMParser I see that parse method and its overloaded versions, only parse files.

How can I parse from a string?

回答1:

Create a MemBufInputSource and parse that:

xercesc::MemBufInputSource myxml_buf(myxml.c_str(), myxml.size(),
                                     "myxml (in memory)");
parser->parse(myxml_buf);


回答2:

Use the following overload of XercesDOMParser::parse():

void XercesDOMParser::parse(const InputSource& source);

passing it a MemBufInputSource:

MemBufInputSource src((const XMLByte*)myxml.c_str(), myxml.length(), "dummy", false);
parser->parse(src);


回答3:

Im doing it another way. If this is incorrect, please tell me why. It seems to work. This is what parse expects:

DOMDocument* DOMLSParser::parse(const DOMLSInput * source )

So you need to put in a DOMLSInput instead of a an InputSource:

xercesc::DOMImplementation * impl = xercesc::DOMImplementation::getImplementation();
xercesc::DOMLSParser *parser = (xercesc::DOMImplementationLS*)impl)->createLSParser(xercesc::DOMImplementation::MODE_SYNCHRONOUS, 0);
xercesc::DOMDocument *doc;

xercesc::Wrapper4InputSource source (new xercesc::MemBufInputSource((const XMLByte *) (myxml.c_str()), myxml.size(), "A name");
parser->parse(&source);