【问题标题】:How to work reliably with XmlReader如何使用 XmlReader 可靠地工作
【发布时间】:2013-03-21 13:58:34
【问题描述】:

我正在使用XmlReader 类,即只进阅读器。我正在调用的方法将光标作为副作用移动。但是,有时该方法会引发异常,并将光标留在意料之外的地方。我该如何处理?

xml.ReadStartElement("root");

if (xml.IsStartElement("Results"))
{
    try
    {
        results = Results.FromXml(xml);
        // if method successful, it reads past the closing tag of the 'Results' element
    }
    catch
    {
        results = null;
        // I want to manually move the cursor past the closing tag of the 'Results' element.
    }
}

示例文档

<root>
    <results>
        <arbitaryxml/>
    </results>*
    <signatures>

如果Results.FromXml 方法成功,光标将留在*。但是,如果失败,它可能会留在结果元素内的任何位置。我希望我的 catch 块确保光标前进到 *. (注意。下一个元素并不总是称为“签名”)。

我发现这很难解释。请询问是否需要澄清,我可以举更多例子。

【问题讨论】:

  • 我觉得异常通常不应该成为程序预期流程的一部分。它们应该是计划好的,是的,但我觉得你应该做一些检查以防止首先抛出异常。
  • 失败的原因是什么?我会解决原因而不是症状。

标签: c# .net xmlreader


【解决方案1】:

看看ReadSubtree 方法,它会做你想做的事。实际上,它定位到结束元素节点,但它完成了你想要的。通常,您会编写如下内容:

XmlReader resultsReader = reader.ReadSubtree();
while (resultsReader.Read())
{
    // process results node here
}

ReadSubtree 返回后,对reader.Read 的调用将返回&lt;/results&gt; EndElement 节点。因此,如果处理结果引发异常,您仍然在正确的位置。

如果ReadSubtree 抛出异常,那当然是无法恢复的。这表明 XML 中存在错误,据我所知,使用 XmlReader 无法可靠地恢复该错误。

【讨论】:

    【解决方案2】:

    Jim 是对的,ReadSubtree 方法有效,尽管它有点繁琐:

    if (xml.IsStartElement("Results"))
    {
        // Be careful so that the cursor will be left after the closing tag of the 'Results' element, even if Results.FromXml throws.
    
        using (XmlReader resultsElement = xml.ReadSubtree())
        {
            resultsElement.Read();
            try 
            {
                results = Results.FromXml(resultsElement);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Reading results xml went wrong {0}", e.Message);
            }
        }
    
        xml.ReadEndElement();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多