将pugixml的result.offset转换为列/行 [英] Convert pugixml's result.offset to column/line

查看:137
本文介绍了将pugixml的result.offset转换为列/行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用pugixml的应用程序的用户友好的错误报告。

我正在使用result.offset。

有没有办法获取行和列?
我可能处理大型XML文件,如果这有差异。

I need user-friendly error reporting for an application that uses pugixml.
I am currently using result.offset.
Is there a way to get the line and column instead? I am potentially dealing with large XML files, if that makes a difference.

推荐答案

此功能不容易在pugixml中,因为在每个解析上执行相对昂贵,并且解析完成后,在一般情况下无法恢复文件/行信息。

This functionality is not readily available in pugixml since it's relatively expensive to do it on every parse, and after parsing is complete it's impossible to recover file/line information in the general case.

这是一个代码片段构建一个偏移 - >线映射,您可以在解析失败的情况下使用,或者由于其他原因需要信息;随时调整文件I / O代码以符合您的要求。

Here's a snippet that builds an offset -> line mapping that you can use in case parsing fails or you need the information for other reasons; feel free to tweak file I/O code to match your requirements.

typedef std::vector<ptrdiff_t> offset_data_t;

bool build_offset_data(offset_data_t& result, const char* file)
{
    FILE* f = fopen(file, "rb");
    if (!f) return false;

    ptrdiff_t offset = 0;

    char buffer[1024];
    size_t size;

    while ((size = fread(buffer, 1, sizeof(buffer), f)) > 0)
    {
    for (size_t i = 0; i < size; ++i)
        if (buffer[i] == '\n')
            result.push_back(offset + i);

    offset += size;
    }

    fclose(f);

    return true;
}

std::pair<int, int> get_location(const offset_data_t& data, ptrdiff_t offset)
{
    offset_data_t::const_iterator it = std::lower_bound(data.begin(), data.end(), offset);
    size_t index = it - data.begin();

    return std::make_pair(1 + index, index == 0 ? offset + 1 : offset - data[index - 1]);
}

这篇关于将pugixml的result.offset转换为列/行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆