将XML字符串反序列化为对象错误:xml文档中存在错误(1,2)

时间:2012-06-28 18:44:56

标签: c# .net windows xml-serialization xmlserializer

从Windows事件查看器中我可以获得以下xml结构:

<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>

我只对xml的EventData部分感兴趣。我创建了以下非常简单的类:

   public class Event
    {
        public EventData EventData;

    }

    public class EventData
    {
        public String[] Data;
    }

然后我使用以下代码:

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

但是在第一行代码中,我收到以下错误:

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

此错误对我没有任何信息。问题是我没有类中的所有字段,或者我是否需要其他类(XmlSerializer除外)来从中获取数据。我希望EventData下的数据的方式是名称和数据值(例如带有data1的name1)......等等

重要编辑 : 我得到的xml是由ToXML()

EventRecord方法生成的

由于

2 个答案:

答案 0 :(得分:7)

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;
}

答案 1 :(得分:3)

XmlSerializer经常告诉你遮罩是什么;添加一些错误处理,特别是:

try {
   // your code
} catch(Exception ex) {
    while(ex != null) {
        Console.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}

猜测这是一个命名空间问题;尝试:

[XmlRoot("Event",
    Namespace="http://schemas.microsoft.com/win/2004/08/events/event")]
public class Event {...}