如何在调用 .LoadXml() 之前检查字符串输入中的有效 xml [英] How to check for valid xml in string input before calling .LoadXml()
问题描述
我更愿意这样做而不在 LoadXml()
中捕获异常并将此结果用作我的逻辑的一部分.关于不涉及自己手动解析 xml 的解决方案的任何想法?我认为 VB 对此函数的返回值为 false 而不是抛出 XmlException.Xml 输入由用户提供.非常感谢!
I would much prefer to do this without catching an exception in LoadXml()
and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much!
if (!loaded)
{
this.m_xTableStructure = new XmlDocument();
try
{
this.m_xTableStructure.LoadXml(input);
loaded = true;
}
catch
{
loaded = false;
}
}
推荐答案
只需捕获异常即可.与解析 XML 相比,捕获异常的小开销淹没了.
Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML.
如果您想要该功能(出于风格原因,而不是为了性能),请自行实现:
If you want the function (for stylistic reasons, not for performance), implement it yourself:
public class MyXmlDocument: XmlDocument
{
bool TryParseXml(string xml){
try{
ParseXml(xml);
return true;
}catch(XmlException e){
return false;
}
}
这篇关于如何在调用 .LoadXml() 之前检查字符串输入中的有效 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!