【问题标题】:Can you Serialize inside a set of Attributes by Set of Attributes?您可以通过一组属性在一组属性内序列化吗?
【发布时间】:2019-07-30 10:22:20
【问题描述】:

我想在一个循环中将一组属性全部序列化为一个 XML 文件。此循环在一组文件夹中运行。根据我当前的实现,它只显示了最后一组属性。

这是我当前的代码,

Student  obj = JsonConvert.DeserializeObject < StudentModel  (File.ReadAllText(file));



string Name = studentModel.name;
string number = studentModel.number;

string testPath = rootDirectory;

XmlSerializer serializer = new XmlSerializer(typeof(StudentModel));
System.IO.StreamWriter writer = new System.IO.StreamWriter(testPath + "\\Test.xml");
serializer.Serialize(writer, studentModel);
writer.Close();

我当前的输出是

<?xml version="1.0" encoding="utf-8"?>
<StudentModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Max</name>
<number>1</number>

</StudentModel>

需要的输出是

<?xml version="1.0" encoding="utf-8"?>
<StudentModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Max</name>
<number>1</number>

</StudentModel>

<StudentModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Amy</name>
<number>2</number>

</StudentModel>

<StudentModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Jack</name>
<number>3</number>

</StudentModel>

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    在我看来,您想要做的是将StudentModel 的列表(或数组)序列化为 xml。目前,您只序列化 StudentModel 的一个实例,并在循环的每次迭代中覆盖生成的 xml,留下最后一项。您可以做的是创建一个具有List()StudentModel 作为属性的类并序列化该类实例,不再需要循环。

    新类中的 List 属性将如下所示:

    [XmlArray("StudentModels"), XmlArrayItem(typeof(StudentModel), ElementName = "StudentModel")] 
    public List<StudentModel> StudentModelList{ get; set; }
    

    【讨论】:

    • 我相信这会起作用@Roland Deschain。感谢帮助
    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 2011-07-17
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多