我想處理空文件,它不包含任何數據 運行下面的代碼後,它會給出錯誤,如根元素丟失。如何檢查xDocument爲空或空的c#
如何檢查xDoc
爲空還是空?
string path = @"E:\Test.xml";
XDocument xDoc = XDocument.Load(path);
我想處理空文件,它不包含任何數據 運行下面的代碼後,它會給出錯誤,如根元素丟失。如何檢查xDocument爲空或空的c#
如何檢查xDoc
爲空還是空?
string path = @"E:\Test.xml";
XDocument xDoc = XDocument.Load(path);
XDocument.Load需要一個有效的XML文件。否則會拋出異常。您可以在調用XDocument.Load之前檢查文件是否存在或爲空,例如通過
if (new System.IO.FileInfo(path).Length > 0)
{
...
}
或者你可以捕捉到異常。
string path = @"E:\Test.xml";
try
{
XDocument xDoc = XDocument.Load(path);
} catch(Exception) {
// some problem
}
如果將此代碼放入靜態函數中,代碼將更具可讀性。
var xDoc = MyXDocument.Load(path);
if (xDoc != null)
{ ....
}
public class MyXDocument {
public static XDocument Load(string path) {
try
{
XDocument xDoc = XDocument.Load(path);
return xDoc;
} catch(Exception) {
return null;
}
}
}
我可以像這樣處理,但需要一些其他方法,我可以檢查XDocument爲空或空 –
@yashfale - 您可以詳細闡述您的問題,爲什麼這些檢查不符合您的要求?如果是風格問題,可以編寫一個靜態幫助器方法,如MyXDocument.Load(),如果在加載過程中發生錯誤,則返回null。 –
瞭解! ,我們必須使用try catch塊。沒有其他方式來檢查空或XDocument空。謝謝。 –
試試這個:http://stackoverflow.com/questions/375590/how-does-one-test-a-file-to-see-if-its-a-valid-xml-file-before它與 – YuvShap
路徑已經存在,但文件是空的,我可以使用嘗試趕上,但需要一些其他方法來檢查特定的XDocument爲空或空 –
它不明白爲什麼try catch塊不會回答你的問題,你能解釋一下你想要的結果嗎? – YuvShap