如何使用 PugiXML 和 boost::iostreams 解析 .xml.gz

在我们的上一篇文章最小 PugiXML 文件读取器示例中,我们提供了一个简短的示例,说明如何使用 PugiXML 从未压缩的 XML 文件读取。实际上,许多大型 XML 文件以 .xml.gz 包形式分发。

由于你可以使用 boost::iostreams 实时解压 gzip 数据并直接管道到 PugiXML,你不需要在硬盘上存储解压后的数据。

pugixml_piped_gz.cpp
#include <iostream>
#include <fstream>
#include <pugixml.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
using namespace std;
using namespace pugi;

int main() {
    // 打开"原始" gzip 压缩数据流
    ifstream file("test.xml.gz", ios_base::in | ios_base::binary);
    // 配置解压器过滤器
    boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
    inbuf.push(boost::iostreams::gzip_decompressor());
    inbuf.push(file);
    //将 streambuf 转换为 istream
    istream instream(&inbuf);
    // 从流解析
    xml_document doc;
    xml_parse_result result = doc.load(instream);
    // 打印根元素内容
    cout << "Load result: " << result.description() << "\n"
         << doc.child("root-element").child_value() // "Test text"
         << endl;
}
CMakeLists.txt
ccmake_minimum_required(VERSION 3.0)
find_package(Boost 1.36.0 COMPONENTS iostreams)

include_directories(${Boost_INCLUDE_DIRS})
add_executable(pugixml-example pugixml-example.cpp)
target_link_libraries(pugixml-example pugixml ${Boost_LIBRARIES})
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root-element>Test text</root-element>

下载所有三个文件然后运行

build_and_run.sh
gzip test.xml
cmake .
make
./pugixml-example

你应该看到类似这样的输出

pugixml_output.txt
Load result: No error
Test text

Check out similar posts by category: Boost, C/C++