有谁知道如何在 try/catch block 中不使用 XmlDocument.LoadXml()
之类的东西来检查字符串是否包含格式正确的 XML?我得到的输入可能是 XML,也可能不是 XML,我希望代码能够识别输入可能不是 XML 而不依赖于 try/catch,以提高速度和一般原则,即非特殊情况不应引发异常(exception)。我目前有执行此操作的代码;
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。这个异常在调试过程中造成了快乐的 hell ,因为每次我检查一个字符串时,调试器都会在这里中断,“帮助”我解决我讨厌的问题。
最佳答案
我不知道没有异常的验证方法,但您可以将调试器设置更改为仅在 XmlException
未处理时中断 - 这应该可以解决您的直接问题,即使代码仍然不优雅。
为此,转到调试/异常.../公共(public)语言运行时异常并找到 System.Xml.XmlException,然后确保只勾选“用户未处理”(而不是抛出)。
关于c# - 不使用 try/catch 检查格式正确的 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026247/