【问题标题】:parse logfile with inconsistent data to XML structure using c#使用 c# 将具有不一致数据的日志文件解析为 XML 结构
【发布时间】:2016-05-10 14:00:06
【问题描述】:

使用thisgreate 教程。

这是一个简单的例子,里面有很多这样的日志文件:

25/05/2002   21:49   Search   Dozer   Anita1
25/05/2002   21:51   Update   Dozer   Anita1
26/05/2002   11:02   Search   Manda   Gerry2k
26/05/2002   11:12   Update   Manda   Gerry2k
27/05/2002   15:34   Search   Anka   Anita1
12/08/2002   10:14   Search   Amber   Huarez

我的日志文件不一致,例如:

25/05/2002   21:49   Search   Dozer   Anita1
25/05/2002   21:51   Update           Anita1
26/05/2002           Search   Manda   Gerry2k
26/05/2002   11:12   Update   Manda   
27/05/2002   15:34             Anka   Anita1
             10:14   Search   Amber   Huarez

如果某些字段为空,我该如何防止异常?

它是一个代码

 xmlFile.Formatting = Formatting.Indented;
        xmlFile.WriteStartDocument();
        xmlFile.WriteStartElement("lines");

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains("\t"))
            {
                string[] items = line.Split('\t');


                xmlFile.WriteStartElement("line");

                xmlFile.WriteElementString("id",items[0]);
                xmlFile.WriteElementString("mandant", items[1]);
                xmlFile.WriteElementString("datetime", items[2]);
                xmlFile.WriteElementString("t_m", items[3]);
                xmlFile.WriteElementString("user", items[4]);
                xmlFile.WriteElementString("action", items[5]);
                xmlFile.WriteElementString("info", items[6]);

                xmlFile.WriteEndElement();
            }
        }

        xmlFile.WriteEndDocument();
        xmlFile.Close();

【问题讨论】:

    标签: c# xml parsing xml-parsing logfile


    【解决方案1】:

    我认为该问题仅在最后一项丢失时出现, 因为中间缺少的项目最后仍然会有一个制表符分隔符。

    在这种情况下,您可能应该使用内联条件来检查您是否存在值:

                xmlFile.WriteElementString("id", (items.Length > 0 ? items[0] : ""));
                xmlFile.WriteElementString("mandant", (items.Length > 1 ? items[1] : ""));
                xmlFile.WriteElementString("datetime", (items.Length > 2 ? items[2] : ""));
                xmlFile.WriteElementString("t_m", (items.Length > 3 ? items[3] : ""));
                xmlFile.WriteElementString("user", (items.Length > 4 ? items[4] : ""));
                xmlFile.WriteElementString("action", (items.Length > 5 ? items[5] : ""));
                xmlFile.WriteElementString("info", (items.Length > 6 ? items[6] : ""));
    

    这样做会在超出记录末尾的插槽中为您提供默认的空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多