有没有人知道如何在不使用 XmlDocument.LoadXml()
的 try/catch 块的情况下检查一个字符串是否包含格式良好的 XML?我有可能是 XML 的输入,也可能不是,我希望代码能够识别到输入可能不是 XML,而不依赖于 try/catch,这样可以提高速度,并且根据一般原则,非异常情况不应该引发异常。我目前已经有了这样的代码;
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。异常在调试过程中会产生严重问题,因为每次检查字符串时,调试器都会在这里中断,"帮助"我解决烦人的问题。