3

我正在尝试将 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.

有谁知道我在这里想念什么?希望有人能帮忙!

问候,

鲍勃

4

1 回答 1

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. 这让生活变得有点复杂。

然后我们注意到您的日期不是“开始时间”/“结束时间”,因此我们可以简化为:

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

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

最后,您的 xml 格式错误 - 您尚未关闭根元素。

坦率地说,序列化程序不喜欢这样我并不感到惊讶 :)

于 2013-04-26T10:53:07.827 回答