Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.Load(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));
    }
}
like image 730
Ashish Gupta Avatar asked May 16 '11 15:05

Ashish Gupta


1 Answers

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.

like image 76
Ryan Gates Avatar answered Oct 18 '22 07:10

Ryan Gates