C#将XML序列化为Object

时间:2013-04-26 10:46:19

标签: c# xml-serialization

我正在尝试将XML序列化为对象。但是,我遇到了一些麻烦。我可能已经在网上发布了关于答案的帖子,但我还没弄清楚。请让我解释一下:

我有以下想要序列化的XML:

<Import_RootObject>
 <Organizations>
  <Import_Organization OrgNr="xxxx">
   <Events>
    <Import_Event StartTime="2012-01-01 09:00:00" EndTime="2012-01-02 12:00:00">
    <Players>
     <Import_Player PersonNummer="1111" />
     <Import_Player PersonNummer="2222" />
     <Import_Player PersonNummer="3333" />
     <Import_Player PersonNummer="4444" />
    </Players>
   </Import_Event>
  </Events>
 </Import_Organization>
</Organizations>

我使用四个类来捕获这个XML:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("Import_RootObject")]
public class Import_RootObject
{
    [XmlArray("organizations")]
    [XmlArrayItem("organizations")]
    public List<Import_Organization> Organizations { get; set; }
}



using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Import_Organization
{
    [XmlAttribute("orgnr")]
    public string OrgNr { get; set; }

    [XmlArray("events")]
    [XmlArrayItem("events")]
    public List<Import_Event> Events { get; set; }

}



using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Import_Event
{
    [XmlAttribute("starttime")]
    public DateTime StartTime { get; set; }
    [XmlAttribute("endtime")]
    public DateTime EndTime { get; set; }

    [XmlArray("players")]
    [XmlArrayItem("players")]
    public List<Import_Player> Players { get; set; }

}



using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Import_Player
{
    [XmlAttribute]
    public string PersonNummer { get; set; }

}

我用来反序列化的代码是:

XmlSerializer serializer = new XmlSerializer(typeof(Import_Organization));
Import_RootObject ei = (Import_RootObject)serializer.Deserialize(new StringReader(sb.ToString()));

我得到的错误是:

There is an error in XML document (1, 2).
<Import_RootObject xmlns=''> was not expected.

有谁知道我在这里缺少什么?希望有人可以帮忙!

此致

鲍勃

1 个答案:

答案 0 :(得分:9)

第一个明显的错误是:

XmlSerializer serializer = new XmlSerializer(typeof(Import_Organization));

当然应该是:

XmlSerializer serializer = new XmlSerializer(typeof(Import_RootObject));

但是,您还应注意xml区分大小写:

[XmlArray("organizations")]
[XmlArrayItem("organizations")]

应该是:

[XmlArray("Organizations")]
[XmlArrayItem("Import_Organization")]

匹配xml;同样

[XmlArray("events")]
[XmlArrayItem("events")]

应该是:

[XmlArray("Events")]
[XmlArrayItem("Import_Event")]

[XmlArray("players")]
[XmlArrayItem("players")]

应该是:

[XmlArray("Players")]
[XmlArrayItem("Import_Player")]

此外,请注意<Players> Import_Event的后代 - 它是Events的一部分。这使生活变得有点复杂。

我们注意到您的日期不是“starttime”/“endtime”,因此我们可以简化为:

[XmlAttribute]
public DateTime StartTime { get; set; }
[XmlAttribute]
public DateTime EndTime { get; set; }

除了......那些日期/时间无效xml日期/时间 - 它们的格式错误。因此,您现在可能必须将这些数据视为string数据。

最后,你的xml格式错误 - 你还没有关闭根元素。

坦率地说,我对串行器不喜欢这一点并不感到惊讶:)