有没有人知道如何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;
}
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不应该需要try/catch.异常是在调试期间导致快乐的地狱,因为每次我检查字符串时调试器都会在这里打破,"帮助"我解决我的麻烦问题.