c#中的复杂XML反序列化

时间:2012-08-15 15:47:01

标签: c# xml-deserialization

这是我的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>

我正在尝试使用类成员上的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; }
}

我知道这段代码期望维度中存在一个实际的“Value”元素。但我找不到.NET库中的任何属性装饰器,可以告诉它使用元素的实际文本,除了XmlText,但我想要一个小数...代理字段是唯一的选择吗? (例如

[XmlText] public string Text { get; set; }

[XmlIgnore]
public decimal Value
{
  get { return Decimal.Parse(this.Text); }
  set { this.Text = value.ToString("f2"); }
}

感谢。

1 个答案:

答案 0 :(得分:3)

您可以使用XmlAttribute作为属性,使用XmlText作为文字。因此,请尝试将public decimal Value更改为使用[XmlText]进行修饰。

[Serializable]
public class Dimension 
{
    [XmlAttribute("units")]
    public string Units { get; set; }   

    [XmlText]
    public decimal Value { get; set; }
}