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塊內的空白?谷歌只拋出了檢查一個字符串是否是空白......
乾杯長久,
格雷厄姆