使用未知数量的嵌套语句解析日志文件

时间:2011-08-15 09:23:17

标签: c# file-io

我有一个日志文件:

begin; x1
begin; y1
end; y1
begin; z1
begin; z2
end; z2
end; z1
end;x1

我希望将此文件解析为可能如下所示的数据结构:

x1 >
    y1
    z1 >
        z2

所以x1事件包含y1& z1事件和z1事件包含z2事件。

在这种情况下是否有可能有用的标准算法?

我想也许递归可能能够通过在每个'begin'语句上分支来正确地解析所有子事件来帮助我。我们将非常感激地收到任何建议。

修改 最终目标是在分层ListView类型组件中的GUI上显示事件。我希望通过能够显示这样的日志文件,可以更好地可视化我系统中的事件序列。

2 个答案:

答案 0 :(得分:1)

我会选择递归下降解析器。

LogTree Parse()
{
    LogTree current = new LogTree();
    if (!ReadBegin(current))
        return null;
    LogTree child = null;
    while ((child = Parse()) != null)
    {
        current.Chilren.Add(Child);
    }
    if (!ReadEnd(current))
        return null;
    return current;
}

bool ReadBegin(LogTree current)
{
    if (nexttoken != "begin")
        return false;
    readNextToken();
    current.Name = nexttoken;
    readNextToken();
    return true;
}

bool ReadEnd(LogTree current)
{
    if (nexttoken != "end")
        return false;
    readNextToken();
    if (current.Name != nexttoken)
        return false;
    readNextToken();
    return true;
}

我们有

class LogTree
{
    public string Name;
    public List<LogTree> Children = new List<LogTree>();
}

答案 1 :(得分:0)

为什么不将它转换为XML作为使用数据的最简单方法:

var xml = XDocument.Parse(string.Join("",text.Replace("; ", ";")
                                .Split(' ')
                                .Select(i => i.StartsWith("begin;") ? 
                                    i.Replace("begin;", "<node>") : "</node>")));