检查格式良好的XML没有一个try / catch? [英] Check well-formed XML without a try/catch?
问题描述
有谁知道我可以检查一个字符串包含格式良好的XML没有在try / catch块使用像 XmlDocument.LoadXml()
?我有输入,可能会或可能不会XML,我想code的认识,认为输入可能不是XML不依赖于一个try / catch,为速度和一般原则,即非特殊情况不该T抛出异常。我现在有code,做这一点;
Does anyone know how I can check if a string contains well-formed XML without using something like XmlDocument.LoadXml()
in a try/catch block? I've got input that may or may not be XML, and I want code that recognises that input may not be XML without relying on a try/catch, for both speed and on the general principle that non-exceptional circumstances shouldn't raise exceptions. I currently have code that does this;
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语句。唯一的例外是在调试过程中引起快乐的地狱,因为我每次检查字符串中的调试器将中断在这里,''帮助我与我的讨厌的问题。
But it seems like something that shouldn't require the try/catch. The exception is causing merry hell during debugging because every time I check a string the debugger will break here, 'helping' me with my pesky problem.
推荐答案
我不知道没有异常确认的一种方式,但您可以更改调试器设置为仅打破 XmlException
如果是未处理的 - 这应解决您的紧迫问题,即使code仍是不雅
I don't know a way of validating without the exception, but you can change the debugger settings to only break for XmlException
if it's unhandled - that should solve your immediate issues, even if the code is still inelegant.
要做到这一点,去调试/例外... /公共语言运行库异常和查找System.Xml.XmlException,然后确保只有用户未处理勾选(没有抛出)。
To do this, go to Debug / Exceptions... / Common Language Runtime Exceptions and find System.Xml.XmlException, then make sure only "User-unhandled" is ticked (not Thrown).
这篇关于检查格式良好的XML没有一个try / catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!