有沒有人知道我可以檢查一個字符串是否包含格式良好的XML,而不是在try/catch塊中使用類似XmlDocument.LoadXml()
的東西?我已經得到了可能或可能不是XML的輸入,並且我希望代碼承認在不依賴try/catch的情況下輸入可能不是XML,無論是速度還是非常規環境都不應該提高的一般原則例外。我目前有這樣的代碼;檢查沒有try/catch的格式良好的XML?
private bool IsValidXML(string value)
{
try
{
// Check we actually have a value
if (string.IsNullOrEmpty(value) == false)
{
// Try to load the value into a document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value);
// If we managed with no exception then this is valid XML!
return true;
}
else
{
// A blank value is not valid xml
return false;
}
}
catch (System.Xml.XmlException)
{
return false;
}
}
但它看起來應該不需要try/catch。在調試過程中,例外情況會導致快樂,因爲每次檢查一個字符串時,調試器都會在這裏中斷,'幫助'解決我的麻煩問題。
如果調試器是你的問題你可以關掉XmlExceptions的用戶操作。使用VS中的快捷鍵:Ctrl + Alt + E,找到System.Xml.XmlException並將其關閉。 – nashwan 2013-01-31 15:40:24