2011-07-26 9 views
1

私は、XMLファイルから情報を読み込んでそれに応じて処理する必要があるユースケースを持っています。問題は、このXMLファイルは技術的に空白または空白でいっぱいにすることができます。これは「情報はありません。何もしません」という意味です。他のエラーは失敗しません。空のファイルからのXElementのロードを適切に処理します。

私は現在の線に沿って何かを考えている:

public void Load (string fileName) 
    { 
     XElement xml; 
     try { 
      xml = XElement.Load (fileName); 
     } 
     catch (XmlException e) { 
      // Check if the file contains only whitespace here 
      // if not, re-throw the exception 
     } 
     if (xml != null) { 
      // Do this only if there wasn't an exception 
      doStuff (xml); 
     } 
     // Run this irrespective if there was any xml or not 
     tidyUp(); 
    } 

このパターンは大丈夫に見えるのか?もしそうなら、ファイルがキャッチブロック内の空白だけを含んでいるかどうかのチェックをどのように実装することを人々は勧めますか? Googleが唯一の文字列が空白の場合のためのチェック... muchly

乾杯を投げ、

グラハム

答えて

2

はまあ、最も簡単な方法は、それが最初の場所では空白ではないことを確認することはおそらくあり、ファイル全体を最初に文字列に読み込むことによって(私はあまりにも巨大ではないと仮定しています)

public void Load (string fileName) 
{ 
    var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); 
    var reader = new StreamReader(stream, Encoding.UTF8, true); 
    var xmlString = reader.ReadToEnd(); 

    if (!string.IsNullOrWhiteSpace(xmlString)) { // Use (xmlString.Trim().Length == 0) for .NET < 4 
     var xml = XElement.Parse(xmlString); // Exceptions will bubble up 
     doStuff(xml); 
    } 

    tidyUp(); 
} 
関連する問題