1

Here's my 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. 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? (e.g.

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

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

Thanks.

devlord
  • 4,054
  • 4
  • 37
  • 55

1 Answers1

3

You can use XmlAttribute for the attribute, and XmlText for the text. So try changing your public decimal Value to be decorated with [XmlText].

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

    [XmlText]
    public decimal Value { get; set; }
}
Bryan Crosby
  • 6,486
  • 3
  • 36
  • 55
  • Thanks, Bryan! I didn't even try that. I just assumed based on the docs that it only supported strings! /facepalm – devlord Aug 15 '12 at 15:58
  • 1
    In addition to Bryan Crosby's answer please note that [Serializable] is for Binary Serialization. Please refer to Marc Gravell's answer here: Serializable Class If you are serializing to XML, you can omit the [Serializable] all together and it will serialize to XML fine without it. – Robert H Aug 15 '12 at 17:05