我有一個while循環遍歷一個XML文件,並且對於其中一個節點「url」,其中有時候有無效值。我在此附上了一個try-catch語句來捕獲任何無效值。問題是,無論何時獲取一個無效值,while循環被終止並且程序在該循環之外繼續。如果找到無效值,我需要while循環繼續讀取XML文件的其餘部分。Try-Catch語句結束while循環讀取C#中的XML文件#
這裏是我的代碼:
XmlTextReader reader = new XmlTextReader(fileName);
int tempInt;
while (reader.Read())
{
switch (reader.Name)
{
case "url":
try
{
reader.Read();
if (!reader.Value.Equals("\r\n"))
{
urlList.Add(reader.Value);
}
}
catch
{
invalidUrls.Add(urlList.Count);
}
break;
}
}
我選擇不包括switch語句的其餘部分,因爲它是不相關的。這裏是我的XML的一個樣本:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<visited_links_list>
<item>
<url>http://www.grcc.edu/error.cfm</url>
<title>Grand Rapids Community College</title>
<hits>20</hits>
<modified_date>10/16/2012 12:22:37 PM</modified_date>
<expiration_date>11/11/2012 12:22:38 PM</expiration_date>
<user_name>testuser</user_name>
<subfolder></subfolder>
<low_folder>No</low_folder>
<file_position>834816</file_position>
</item>
</visited_links_list>
我能在整個代碼中的例外是類似以下內容:
「」」,十六進制值0×05,是無效字符3887線,位置13.」
什麼是異常,你確定無效輸入是在你的一個案例中嗎?如果它發生在循環頂部的'reader.Read()'調用中,那麼'try' /'catch'塊將無濟於事。另外,如果實際的XML語法無效,那麼無論您做什麼,XmlTextReader都將無法繼續。 –