使用c#解析具有不一致数据到XML结构的日志文件

时间:2016-05-10 14:00:07

标签: c# xml parsing xml-parsing logfile

使用this greate教程。

这是一个简单的例子,填充日志文件如下:

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

如果某些字段为空,我可以阻止异常? enter image description here

它的代码

 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();

1 个答案:

答案 0 :(得分: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] : ""));

这样就可以在超出记录结尾的插槽中为您提供默认的空字符串。

相关问题