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));
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With