2016-05-10 17 views
0

を使用してthis greate tutorialを使用してください。XML構造と矛盾するデータを持つログファイルを解析します.C#

それこのような偉大な充填ログファイルと簡単な例:いくつかのフィールドが空の場合私は例外を防止することができるもの

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 

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 

私のような矛盾したログファイルがありますか? 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

途中で不足している項目は、まだ終わりでタブ区切り文字を持っているであろうから、私は 、最後の項目が欠落しているとき、問題がのみ発生することを想定したいです。この場合

、あなたはおそらく、あなたが存在する値を持っていることを確認するために、条件付きインラインを使用する必要があります。

  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] : "")); 

はこれをSoingあなたは、レコードの終わりを過ぎているスロットに空の文字列をデフォルト与えます。

関連する問題