反序列化相对路径 XML [英] Deserializing relative path XML
问题描述
在 C# 中,我想反序列化一些相对位置很重要的 Xml.以下 XML 来自名为 Onix 的书籍标准:
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>
如您所见,每 2 行都称为接近度".这些字段与上面的字段一致.
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; }
但是4个邻近字段与之前的字段紧密绑定,每对字段都不是强制性的.例如.您可以获得缺少前两行的 xml.
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?
推荐答案
您正在使用 Order 属性.
将 int
标记为 int?
并将所有字段标记为 Nullable:
You were on your way with the Order attributes.
Mark the int
s 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 应该能够处理这个问题.
XmlSerializer should be able to deal with this.
这篇关于反序列化相对路径 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!