Deserializing relative path XML

我的未来我决定 提交于 2019-12-11 08:46:10

问题


In C# I would like to deserialize some Xml where the relative location is important. The following Xml is from a book standard called Onix:

<Stock>
  <OnHand>1</OnHand>
  <Proximity>xx</Proximity>
  <Reserved>2</Reserved>
  <Proximity>yy</Proximity>
  <OnOrder>3</OnOrder>
  <Proximity>zz</Proximity>
  <Cbo>4</Cbo>
  <Proximity>zz</Proximity>
</Stock>

As you can see every 2nd line is called "Proximity". These fields goes with the field above.

If all fields were mandatory then it would be no problem, and the code would look like this:

[XmlElement("OnHand", Order = 0)]public int OnHand { get; set; }
[XmlElement("Proximity", Order = 1)] public string OnHandProximity { get; set; }

[XmlElement("Reserved", Order = 2)] public int Reserved { get; set; }
[XmlElement("Proximity", Order = 3)] public string ReservedProximity { get; set; }

[XmlElement("OnOrder", Order = 4)] public int OnOrder { get; set; }
[XmlElement("Proximity", Order = 5)] public string OnOrderProximity { get; set; }

[XmlElement("CBO", Order = 6)] public int Cbo { get; set; }
[XmlElement("Proximity", Order = 7)] public string CboProximity { get; set; }

But the 4 proximity fields are tightly bound to the field before, and each pair of fields are not mandatory. E.g. you can get xml where the first 2 lines are missing.

Are there any Attributes intended for for these kinds of problems?


回答1:


You were on your way with the Order attributes.
Mark the ints as int? and all fields as Nullable:

    [XmlElement("OnHand", Order = 0, IsNullable = true)]
    public int? OnHand { get; set; }

    [XmlElement("Proximity", Order = 1, IsNullable = true)]
    public string OnHandProximity { get; set; }

XmlSerializer should be able to deal with this.



来源:https://stackoverflow.com/questions/54885976/deserializing-relative-path-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!