2011-07-26 27 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(); 
    } 

請問這種模式似乎還好嗎?如果是這樣,那麼人們如何建議實施檢查,以確定該文件是否僅包含catch塊內的空白?谷歌只拋出了檢查一個字符串是否是空白......

乾杯長久,

格雷厄姆

回答

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