如何使用 libxml++ 解析 XML 字符串而不是 XML 文件

How to parse XML string instead of XML file with libxml++

我正在尝试在我的 C++ 程序中解析包含 XML 文档的字符串。我知道我可以用 C using libxml2 做到这一点,但我想要一个使用 libxml++ 的 C++ 解决方案(它建立在 libxml2 之上)。

目前,我可以像这样从文件中解析:

DomParser *parser = new DomParser;
parser->parse_file("sample.xml");

答案很简单(几乎与解析文件相同)。

parser->parse_memory(xml_document);

在我的例子中,我需要同时支持两者的选项,所以这就是我想出的解决方案。

ifstream input_stream;
input_stream.open(xml.c_str(), ios::in); // attempt to open the file for reading 
if(input_stream.fail())
{
    parser->parse_memory(xml); // is not a file, parse as a string
} 
else
{
    parser->parse_file(xml); // is a file, parse as a file
}