Making Xerces parse a string instead of a file

梦想与她 提交于 2019-11-27 20:59:15

问题


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);


来源:https://stackoverflow.com/questions/4691039/making-xerces-parse-a-string-instead-of-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!