如何在不使用XmlException的情况下检查XmlDocument实例上的LoadXml()是否出错

时间:2013-04-30 15:04:39

标签: c# xml xmldocument

我必须修复一些看起来像这样的代码:

XmlDocument XmlFoo = null;

try{
    SomeUntrappedWCFCalls();
    SomeUntrappedStringParsing();
    SomeUntrappedXMLParsing();
    ..
    XmlFoo = new XmlDocument();
    XmlFoo.LoadXml(SomeXml);
    ..
    SomeUntrappedWCFCalls();
    SomeUntrappedStringParsing();
    SomeUntrappedXMLParsing();
}
(Exception ex){

      CodeThatDealsWithPartOfTheExceptionsRaisedAbove(); 
      ..
      //Need to check if the LoadXml() went wrong
      ..
      CodeThatDealsWithPartOfTheExceptionsRaisedAbove();
}

如果XmlFooXmlDocument的新实例,但LoadXml()出错,我怎样才能正确检查异常处理部分(*)加载/解析错误?

我有两个约束:

  1. 我无法将LoadXML()包装在XmlException内,因为所有错误处理都在Exception代码中处理。
  2. 我无法在一般异常之前创建XmlException因为在XmlFoo解析之前和之后解析了其他Xml文件。
  3. 使用以下内容计算节点数是否是一种安全且不优雅的解决方法:

    if (XmlFoo.ChildNodes.Count == 0){..
    

    还是我需要一些其他变量以某种方式检查LoadXML()解析状态?

3 个答案:

答案 0 :(得分:1)

我只是在猜这里,但是在看了Jon Skeet的评论之后,也许这么简单,因为这可以帮到你:

XmlDocument XmlFoo = null;
bool loading = false;
try{
    ..
    XmlFoo = new XmlDocument();
    loading = true;
    XmlFoo.LoadXml(SomeXml);
    loading = false;
    ..
}
catch (Exception ex){

   if(loading)
   {
      //something went wrong while loading XML
   }   .. 
}

答案 1 :(得分:1)

鉴于你的可怕限制,我认为最干净的解决方案是:

bool parsingAttempted = false;
bool parsingSucceeded = false;
try
{
    XmlFoo = new XmlDocument();
    parsingAttempted = true;
    XmlFoo.LoadXml(SomeXml);
    parsingSucceeded = true;
}

现在您可以检查三种情况:

  • 尝试解析前出错:parsingAttempted为false
  • 解析时出错:parsingAttempted为真,parsingSucceeded为假
  • 解析成功:parsingSucceeded为真

答案 2 :(得分:0)

不确定为什么你不能抓住XmlException,看看这个:

XmlDocument XmlFoo = null;

try
{
    XmlFoo = new XmlDocument();
    XmlFoo.LoadXml(SomeXml);
}
(XmlException ex)
{
    // Loadxml went wrong
}
(Exception ex)
{
    // Some other Error
}

或者您也可以使用:

XmlDocument XmlFoo = null;

try
{
    XmlFoo = new XmlDocument();
    XmlFoo.LoadXml(SomeXml);
}
(Exception ex)
{
    if(ex is XmlException)
        // LoadXml Error
    else
        // Some other Error
}