错误:- 在XDocument.Load上XmlReader的状态应该是Interactive。

12

我遇到了以下错误:

System.InvalidOperationException: XmlReader的状态应该是Interactive。 在以下代码中: System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o) at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)

请问有谁能指出我在这里错了吗?

static XDocument GetContentAsXDocument(string xmlData)
{
    XmlDocument xmlDocument = new XmlDocument();
    if (!string.IsNullOrEmpty(xmlData))
    {
        xmlDocument.LoadXml(xmlData);
        return xmlDocument.ToXDocument();
    }
    else
    {
        return new XDocument();
    }
}


/// <summary>
///  Converts XMLDocument to XDocument
/// </summary>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public static XDocument ToXDocument( this XmlDocument xmlDocument )
{
    using( var nodeReader = new XmlNodeReader( xmlDocument ) )
    {
        nodeReader.MoveToContent();
        return XDocument.Load(
             nodeReader,
            (LoadOptions.PreserveWhitespace |
             LoadOptions.SetBaseUri |
             LoadOptions.SetLineInfo));
    }
}

如果不调用MoveToContent会发生什么?我目前无法自行测试。 - Jon Skeet
@Jon,根据http://msdn.microsoft.com/en-us/library/bb538465.aspx的要求,已经添加了这个功能。我会再次检查并更新。 - Ashish Gupta
2
@user7401431:啊——知道之前它并不总是失败会很好。在这种情况下,您应该绝对查看MoveToContent的结果,并比较失败和工作情况中的值。 - Jon Skeet
1
在此期间,您可以在MoveToContent()之后打印nodeReader.ReadState。您是否有一个失败的示例文件?我尝试了几个文档,但都成功了。 - Johan Larsson
只是提醒一下。我在尝试对从存储过程返回的XmlReader执行XElement.ReadFrom()时遇到了错误。执行MoveToContent()将读取器置于“交互”状态,然后ReadFrom()可以正确地读取XML。 - redcalx
显示剩余2条评论
1个回答

3
你应该使用 XDocument.ParseXmlDocument.OuterXml。请参考下面的示例。
public static XDocument ToXDocument( this XmlDocument xmlDocument )
{
    string outerXml = xmlDocument.OuterXml;
    if(!string.IsNullOrEmpty(outerXml))
    {
        return XDocument.Parse(outerXml, (LoadOptions.PreserveWhitespace |
             LoadOptions.SetBaseUri |
             LoadOptions.SetLineInfo));
    }
    else
    {
        return new XDocument();
    }
}

您可以在此处找到其他将XmlDocument转换为XDocument的方法(链接)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接