[英]Complex XML deserialization in c#
Here's my blob: 这是我的blob:
<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>
I'm trying to deserialize it using xml attributes on my class members, but I'm having trouble. 我正在尝试使用我的类成员上的xml属性对其进行反序列化,但我遇到了麻烦。 I'm trying to use a "Dimensions" type with a unit and value.
我正在尝试使用具有单位和值的“尺寸”类型。 How do I get the unit as an attribute and get the value to the value?
如何将单位作为属性并获取值的值?
Here's what I'm trying: 这是我正在尝试的:
[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; }
}
I know that this code is expecting an actual "Value" element inside the dimension. 我知道这段代码期望维度中的实际“值”元素。 But I can't find any attribute decorators in the .NET library that could tell it to use the actual text of the element for this, other than XmlText, but I want a decimal... Is a proxy field the only option?
但我找不到.NET库中的任何属性装饰器,可以告诉它使用元素的实际文本,除了XmlText,但我想要一个小数...代理字段是唯一的选择吗? (eg
(例如
[XmlText] public string Text { get; set; }
[XmlIgnore]
public decimal Value
{
get { return Decimal.Parse(this.Text); }
set { this.Text = value.ToString("f2"); }
}
Thanks. 谢谢。
You can use XmlAttribute
for the attribute, and XmlText
for the text. 您可以使用
XmlAttribute
作为属性,使用XmlText
作为文本。 So try changing your public decimal Value
to be decorated with [XmlText]
. 因此,请尝试使用
[XmlText]
更改您的public decimal Value
。
[Serializable]
public class Dimension
{
[XmlAttribute("units")]
public string Units { get; set; }
[XmlText]
public decimal Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.