1
這裏是我的斑點:複雜的XML序列化
<Attributes>
<SomeStuff>...</SomeStuff>
<Dimensions>
<Weight units="lbs">123</Weight>
<Height units="in">123</Height>
<Width units="in">123</Width>
<Length units="in">123</Length>
</Dimensions>
</Attributes>
我試圖使用XML反序列化它在我的類成員的屬性,但我有麻煩了。我正在嘗試使用帶有單位和值的「維度」類型。我如何獲得單位作爲屬性,並獲得價值?
這裏就是我想:
[Serializable]
public class Attributes
{
public object SomeStuff { get; set; } // Not really...
public Dimensions Dimensions { get; set; }
}
[Serializable]
public class Dimensions
{
public Dimension Height { get; set; }
public Dimension Weight { get; set; }
public Dimension Length { get; set; }
public Dimension Width { get; set; }
}
[Serializable]
public class Dimension
{
[XmlAttribute("units")]
public string Units { get; set; }
[XmlElement]
public decimal Value { get; set; }
}
我知道這個代碼是期待尺寸內的實際「價值」的元素。但我無法找到.NET庫中的任何屬性裝飾器,它可以告訴它使用該元素的實際文本,而不是XmlText,但我想要一個小數...是代理字段唯一選項嗎? (如
[XmlText] public string Text { get; set; }
[XmlIgnore]
public decimal Value
{
get { return Decimal.Parse(this.Text); }
set { this.Text = value.ToString("f2"); }
}
感謝。
謝謝你,布萊恩!我甚至沒有嘗試過,我只是假設它基於文檔,它只支持字符串!/ facepalm – devlord 2012-08-15 15:58:28
除了Bryan Crosby的回答,請注意[Serializable]是用於二進制序列化。 請參考Marc Gravell的答案:可序列化類 如果您序列化爲XML,則可以一起省略[Serializable],它將在沒有它的情況下序列化爲XML。 – 2012-08-15 17:05:30