Reputation: 12004
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>
Upvotes: 15
Views: 10034
Reputation: 4135
Another late answer, but I ran into a problem with the reader.ReadSubtree()
workaround and this ended up working for my situation. The basic approach is reading into a string, then calling XDocument.Parse()
:
XDocument doc;
var textReader = reader as XmlTextReader;
if (textReader != null)
{
var xml = textReader.ReadOuterXml();
doc = XDocument.Parse(xml);
}
else
doc = XDocument.Load(reader);
Upvotes: 0
Reputation: 1077
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());
}
Upvotes: 41
Reputation: 20200
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.
Upvotes: 4