0

使用 System.Xml.Serialization 我正在尝试读取以下结构中的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<rootname xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AListItem>
    <someDataItem>1</someDataItem>
    <anotherItem>2</anotherItem>
  </AListItem>
  <AListItem>
    <someDataItem>3</someDataItem>
    <anotherItem>4</anotherItem>
  </AListItem>
  <Name>a string</Name>
</rootname>

我的班级结构:

public class rootname
{
    public rootname() { }

    [XmlElement("AListItem")]
    List<AListItem> DataList { get; set; }

    public string Name { get; set; }
}

public class AListItem
{
    public AListItem() {}

    public string someDataItem { get; set; }
    public string anotherItem { get; set; }
}

反序列化:

using (System.IO.FileStream stream = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read))
{
    System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(rootname));
    rootname deserializedObject = xml.Deserialize(stream) as rootname;
}

'Name' 属性已加载,但 DataList 为空。应该如何加载 AListItem 项?XmlElement 属性是否正确?

4

1 回答 1

0

谢谢托尼,我刚刚意识到问题所在。我忘记公布名单了!

public class rootname
{
    public rootname() { }

    [XmlElement("AListItem")]
    public List<AListItem> DataList { get; set; } // <<< public!

    public string Name { get; set; }
}

哎呀。

于 2012-07-09T12:54:00.247 回答