Deserialize XML string to Object Error : There is an Error in xml document (1,2)

Saher Ahwal picture Saher Ahwal · Jun 28, 2012 · Viewed 21.4k times · Source

From windows event viewer I can get the following xml structure:

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
  <Provider Name="XXXXXXXXXX" Guid="{YYYYYYYY}" /> 
  <EventID>XYZ</EventID> 
  <Version>0</Version> 
  <Level>L</Level> 
  <Task>A</Task> 
  <Opcode>0</Opcode> 
  <Keywords>0x000xyzh</Keywords> 
  <TimeCreated SystemTime="2012-06-28T15:44:04.997837000Z" /> 
  <EventRecordID>153</EventRecordID> 
  <Correlation ActivityID="{DDDDDDDDD}" /> 
  <Execution ProcessID="199999" ThreadID="90990" /> 
  <Channel>Microsoft-Windows-ABCDEFG/Admin</Channel> 
  <Computer>myPC</Computer> 
  <Security UserID="ABCABC" /> 
  </System>
<EventData>
  <Data Name="name1">data1</Data> 
  <Data Name="name2">data2</Data> 
  <Data Name="name3">data3</Data> 
</EventData>
<RenderingInfo Culture="en-US">
  <Message>some message </Message> 
  <Level>Information</Level> 
  <Task>XYZ</Task> 
  <Opcode>Info</Opcode> 
  <Channel /> 
  <Provider /> 
  <Keywords>
  <Keyword>XYZ</Keyword> 
  </Keywords>
</RenderingInfo>
</Event>

I am only interested in the EventData section of the xml. I have created the following very simple classes:

   public class Event
    {
        public EventData EventData;

    }

    public class EventData
    {
        public String[] Data;
    }

I then use the following code:

XmlSerializer serializer = new XmlSerializer(typeof(Event));
StringReader reader = new StringReader(evtXml);
evt = (Event)serializer.Deserialize(reader);

but on the first line of code, I get the following error:

There is an error in XML document (1, 2).

This error is not informative to me. Is the problem that I don't have all the fields in the classes or do I need some other class (other than XmlSerializer) to get the data from. The way I would like the data under the EventData is by name and data value (e.g name1 with data1) ...etc

Important EDIT: the xml I am getting is generated by the ToXML() method of the EventRecord class

Thanks

Answer

Markus Jarderot picture Markus Jarderot · Jun 28, 2012
XmlSerializer serializer = new XmlSerializer(typeof(Event),
        "http://schemas.microsoft.com/win/2004/08/events/event");

StringReader reader = new StringReader(evtXml);
var evt = (Event)serializer.Deserialize(reader);
public class Event
{
    public Data[] EventData;
}

public class Data
{
    [XmlAttribute]
    public string Name;

    [XmlText]
    public string Value;
}