C#中通过XmlSerializer类反序列化多个同名的XML元素
我有一个 XML 表单,
<BackupSchedule>
<AggressiveMode>0</AggressiveMode>
<ScheduleType>0</ScheduleType>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>1</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<WindowStart>480</WindowStart>
<WindowEnd>1020</WindowEnd>
<ScheduleInterval>0</ScheduleInterval>
</BackupSchedule>
我需要反序列化它,更改其内容,然后将其保存回来。我在阅读 ScheduledDay 元素时遇到问题。 我的类就像
public class BackupScheduleSettings
{
public BackupScheduleSettings()
{
ScheduledDay = new int[7];
}
.....
public int[] ScheduledDay { get; set; }
.....
}
现在,当我加载具有正确 ScheduledDay 值的 XML 内容时,我的类数组仍然为 NULL。
我无法修改 XML 的内容/格式,因为它是遗留代码。我不想使用 XDocument 读取该值,因为它是一个很大的 XML,并且我需要再次序列化它。
我已经搜索了很多而没有任何帮助。任何想法都将受到高度赞赏。
谢谢...
I have an XML in the form
<BackupSchedule>
<AggressiveMode>0</AggressiveMode>
<ScheduleType>0</ScheduleType>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>1</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<ScheduledDay>0</ScheduledDay>
<WindowStart>480</WindowStart>
<WindowEnd>1020</WindowEnd>
<ScheduleInterval>0</ScheduleInterval>
</BackupSchedule>
I need to deserialize it, change its contents and than save it back. I am facing problem in reading ScheduledDay element.
My class is like
public class BackupScheduleSettings
{
public BackupScheduleSettings()
{
ScheduledDay = new int[7];
}
.....
public int[] ScheduledDay { get; set; }
.....
}
Now when I load XML content which has right values for ScheduledDay, my class array is still NULL.
I can't modify the content/format of XML since it is legacy code. I don't want to use XDocument to read the value since it is a large XML and I need to serialize it again.
I have searched a lot without any help. Any ideas will be highly appreciated.
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要
XmlArrayItem
。您希望在没有父元素的情况下序列化 int 数组,这意味着您应该使用XmlElement
修饰数组本身。由于您有特定的订单,因此您需要使用 XmlElement 属性上的Order
值。这是经过相应修改的类:这是生成的 XML:
You don't want
XmlArrayItem
. You want the array of ints to be serialized without a parent element, which means you should decorate the array itself withXmlElement
. Because you have a particular order, you will want to use theOrder
value on the XmlElement attribute. Here's the class, modified accordingly:Here's the generated xML:
装饰你的财产:
Decorate your property:
您只需执行以下操作即可使其正常工作:
通过添加此属性,每次(反)序列化程序看到 ScheduledDay 元素时,它都会知道将其添加到此数组中。
You should just have to do the following for this to work:
By adding this attribute, every time the ScheduledDay element is seen by the (de)serializer it will know to add it to this array.