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

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

本文关键字:XML 文件 字符串 libxml++ 解析 何使用      更新时间:2023-10-16

我正在尝试解析C++程序中包含XML文档的字符串。我知道我可以使用 libxml2 用 C 做到这一点,但我想要一个使用 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
}