开发者

Error :- The XmlReader state should be Interactive on XDocument.Load

开发者 https://www.devze.com 2023-03-06 12:17 出处:网络
I get the following error :- System.InvalidOperationException: The XmlReader state should be Interactive.

I get the following error :-

System.InvalidOperationException: The XmlReader state should be Interactive. at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o) at System.Xml.Linq.XDocument.Loa开发者_运维百科d(XmlReader reader, LoadOptions options)

in the following code. Could anybody point me what I doing wrong here?

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));
    }
}


You should use XDocument.Parse and XmlDocument.OuterXml. See the example below.

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();
    }
}

Other methods of converting from XmlDocument to XDocument can be found here.

0

精彩评论

暂无评论...
验证码 换一张
取 消