5

I am trying to load an xml into an XDocument object.

public void ValidateRules(XmlReader xml)
{
    xml.MoveToContent();
    XDocument xDoc = new XDocument();
    xDoc = XDocument.Load(xml);
}

But, I keep getting the error "The XmlReader state should be Interactive". I searched for a work around for this, and added MoveToContent() method at the top(as it was mentioned that, this will change the ReadState to Interactive), but it didn't work. ReadState is read-only and I cannot change the value.

What can be the problem over here?

P.S. The XML file which I am trying to load has a DTD reference. It is present at the same path as the XML. Do not know whether this is of any significance.

  • 1
    If you have to use XmlReader, check this out: http://stackoverflow.com/questions/2441673/reading-xml-with-xmlreader-in-c-sharp . If you can load xml from file: xDoc = XDocument.Load(string URI); – Arie Sep 05 '14 at 08:58

2 Answers2

3

XML data is null attempt read via reader. reader's ReadState situation will be Initial or EndOfFile (https://msdn.microsoft.com/en-us/library/fxtcxd31.aspx)

public void ValidateRules(XmlReader reader)
{
    XDocument xDoc = XDocument.Load(reader);
}
Developer33
  • 97
  • 1
  • 4
1

Given the signature of your function, you could do:

var xDoc = XDocument.Parse(xml.ReadOuterXml());

Alternatively, if it's not required by your design, don't use a XmlReader - if it's not required by something outside the code you've shown, you can skip the additional layer of abstraction and simply use:

var xDoc = XDocument.Load(PATH_TO_YOUR_FILE);

or

var xDoc = XDocument.Parse(YOUR_XML_STRING);
decPL
  • 5,384
  • 1
  • 26
  • 36
  • I tried this code. But it looks like it does not look for DTD which I have referenced in the xml. It is giving me the following error :- "Reference to undeclared entity 'copy'. Line 17, position 8". 'copy' is an entity which is defined in the DTD. – Ashwin Venkatesh Prabhu Sep 08 '14 at 05:58
  • @AshwinPrabhu Which code exactly? Those are 3 distinct code lines. Could you also post your xml for reference? – decPL Sep 08 '14 at 07:21