Xml序列化嵌套类
本文关键字:嵌套 序列化 Xml | 更新日期: 2023-09-27 18:13:57
我很抱歉,但我检查了每一个例子,我可以,没有得到任何帮助。我的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>
这是我的类,包含其他类的对象,为了简单起见,我从类和xml中删除了很多对象
[XmlRoot("Project")]
[Serializable()]
public class Project
{
[XmlElement("Model")]
public Model Model { get; set; }
[XmlElement("Structure")]
public Structure Structure { get; set; }
//...more objects
}
这是我的Project类
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是Model的列表,两者都被标记为[Serilizable()], Sections是Section的列表,两者都被标记为[Serilizable()] .
我花了一些时间在上面,因为我认为这将是不到30分钟的工作,但运气不好。
任何帮助都将非常感谢
Thanks in advance
在您的XML中,Models
是Model
的数组,但这在您的Project
类中没有正确反映。你需要修改
[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; }
}