Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load XmlReader into XDocument

Tags:

c#

linq-to-xml

I'm trying to load an XmlReader into an XDocument for easier manipulation. The XML is well formed and valid (I double checked). When I try and load it into the XDocument, I get an InvalidOperationException

The XmlReader state should be EndOfFile after this operation.

the code to load this is

public void ReadXml(System.Xml.XmlReader reader)
{
    var doc = XDocument.Load(reader);
}

I've included a sample of the XML that causes the problem. I can serialize and deserialize this class without a problem, but not load it. Any ideas?

<?xml version="1.0" encoding="utf-8"?>
<ForestView xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Forest>
 <TreeNodeView>
  <Level>Master</Level>
  <ID>39476b1f-e2f8-4d76-b82e-a5166899ad43</ID>
  <Name>Black Mesa</Name>
  <ServerIPAddress>127.0.0.1</ServerIPAddress>
  <ServerPortNumber>8000</ServerPortNumber>
  <ClientIPAddress>NA</ClientIPAddress>
  <ClientPortNumber>4000</ClientPortNumber>
  <Nodes>
    <Level>Server</Level>
    <NodeID>062c3e03-235d-4d7d-9b60-c6228c9cc89e</NodeID>
    <Name />
    <ServerIPAddress>127.0.0.1</ServerIPAddress>
    <ServerPortNumber>5000</ServerPortNumber>
    <ClientIPAddress>127.0.0.1</ClientIPAddress>
    <ClientPortNumber>4000</ClientPortNumber>
  </Nodes>
  <Nodes>
    <Level>Intermediate</Level>
    <NodeID>9bafdc9e-771e-42cf-8f03-e7e75a67a6d1</NodeID>
    <Name>Jen</Name>
    <ServerIPAddress>127.0.0.1</ServerIPAddress>
    <ServerPortNumber>8001</ServerPortNumber>
    <ClientIPAddress>127.0.0.1</ClientIPAddress>
    <ClientPortNumber>8000</ClientPortNumber>
    <Nodes>
      <Level>Terminal</Level>
      <NodeID>72509141-0ab8-45c1-8042-30afb233b4a8</NodeID>
      <Name>Mary</Name>
      <ServerIPAddress>127.0.0.1</ServerIPAddress>
      <ServerPortNumber>0</ServerPortNumber>
      <ClientIPAddress>127.0.0.1</ClientIPAddress>
      <ClientPortNumber>8001</ClientPortNumber>
    </Nodes>
   </Nodes>
  </TreeNodeView>
 </Forest>
</ForestView>
like image 715
Steve Avatar asked Jul 15 '09 20:07

Steve


2 Answers

Quite late answer, in case somebody is having the same issue. You can fix it by using ReadSubtree() on the reader, like:

public void ReadXml(System.Xml.XmlReader reader)
{
     var doc = XDocument.Load(reader.ReadSubtree());
}
like image 94
Ruslan Avatar answered Oct 23 '22 21:10

Ruslan


This error implies that there is extra data after the reader has loaded what it thinks is an XML document. Please verify that your XML file contains no data after the final closing element and that the XmlReader is initialized to read from the root element or start of the file, and nothing else.

like image 4
Steve Guidi Avatar answered Oct 23 '22 20:10

Steve Guidi