Getting exception reading an XML node into a c# 4.0 class. Exception: "Message= was not expected.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am getting an exception reading an XML node into a c# 4.0 class. Exception: "Message=<MyData xmlns=> was not expected.
Error:
<span style="color:windowtext; font-family:Courier New; font-size:10pt InnerException: System.InvalidOperationException
<p style="line-height:normal; margin-bottom:0pt <span style="color:windowtext; font-family:Courier New; font-size:10pt <span>
<span style="background:yellow Message=<MyData xmlns=> was not expected.

I do not receive an error if I read in the entire file into the “MyData” class but do if I read in a node “MySitePatient”.<span>

I created a class file from XSD based on this XML snippet:

<pre class="prettyprint <?xml version="1.0" encoding="utf-8"?>
<MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" versionDate="2010-12-09" dataBeginDate="2011-06-24" dataEndDate="2011-07-26" extractedWho="NETWORK SERVICE" extractedWhen="2011-07-25T08:02:01
<Site MySiteCode_key="99
<SitePatient MyPatient_key="9999 [/code]
The c# class generated by the xsd.exe tool does not define the schema elements in the xml above (xmlns:xsi, xmlns:xsd). Those schema elements are not defined in the XSD and that explains the error AFAIK.<span>
What is the best way to avoid this error?<span> Is adjusting the auto generated class the only or best way? If yes, how do I do that?
<p style="line-height:normal; margin-bottom:0pt
<pre class="prettyprint // Deserialize XML file and populate the c# auto generated class from xsd.exe
toolser = new XmlSerializer(typeof(MyData));
MyData data;
using (XmlReader reader = XmlReader.Create(GvXMLFullPath))
{
data = (MyData)ser.Deserialize(reader); // works great!
}

ser = new XmlSerializer(typeof(MySitePatient));
MySitePatient sp;
using (XmlReader reader = XmlReader.Create(GvXMLFullPath))
{
sp = (MySitePatient)ser.Deserialize(reader); // error: <MyData xmlns=> was not expected
}[/code]
<br/>

<p style="line-height:normal; margin-bottom:0pt <span style="color:windowtext; font-family:Consolas
<br/>
<br/>
<br/>

View the full article
 
Back
Top