Xml 序列化嵌套 类

Xml Serilization Nested Classes

抱歉,我检查了所有可能的示例,但没有得到任何帮助。 我应该是 xml 结构是

<?xml version="1.0"?>
<Project ModelVersion="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Models>
    <Model>
      <Id>987214</Id>
      <prop1></prop1>
      <prop2></prop2>
      <Sections>
        <Section>
          <id>3548A</id>
          <prop1>true</prop1>
          <BaseSection xsi:type="Multiple">
            <prop1>Ijk</prop1>
            <prop2>Lmn</prop2>
          </BaseSection>
        </Section>
        <Section>
          <id>3548B</id>
          <prop1>true</prop1>
          <BaseSection xsi:type="Single">
            <prop1>Xyz</prop1>
            <prop2>Abc</prop2>
          </BaseSection>
        </Section>
      </Sections>
    </Model>
  </Models>
</Project>

这是我的 class,其中包含其他 classes 的对象,为了简单起见,我从 classes 和 xml 中删除了很多对象

[XmlRoot("Project")]
[Serializable()]
public class Project
{
    [XmlElement("Model")]
    public Model Model { get; set; }

    [XmlElement("Structure")]
    public Structure Structure { get; set; }

    //...more objects
}

这是我的项目class

Project settings = null;
Stream stream = File.Open(folderPath + filename, FileMode.Open);
XmlSerializer xs = new XmlSerializer(typeof(Project));
settings = (Project)xs.Deserialize(stream);
stream.Close();

现在我的问题是执行这部分代码后,设置确实包含 'Models' 但它不包含模型的详细信息。模型是模型列表,都标记为 [Serilizable()],部分是部分列表,都标记为 [Serilizable()] 也..

我花了一些时间在上面,因为我认为这将不会是 30 分钟的工作,但运气不好..

任何帮助将不胜感激

提前致谢

在您的 XML 中,ModelsModel 的数组,但这在您的 Project class 中没有正确反映。你需要改变

[XmlElement("Model")]
public Model Model { get; set; }

[XmlArray("Models")]
public List<Model> Models { get; set; }

这将告诉序列化程序将 Models 视为一个数组,这就是它在输入中的表示方式。这对于 Sections 也是一样的:

[Serializable]
public class Model
{
    [XmlElement("Id")]
    public int Id { get; set; }

    [XmlArray("Sections")]
    public List<Section> Sections { get; set; }
}