有没有人知道我可以检查一个字符串是否包含格式良好的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