【问题标题】:Complex XML deserialization in c#c#中复杂的XML反序列化
【发布时间】:2012-08-15 15:47:01
【问题描述】:

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

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

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

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

谢谢。

【问题讨论】:

    标签: c# xml-deserialization


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,布莱恩!我什至没有尝试过。我只是根据文档假设它只支持字符串! /掌脸
    • 除了 Bryan Crosby 的回答,请注意 [Serializable] 用于二进制序列化。请在此处参考 Marc Gravell 的回答:Serializable Class 如果要序列化为 XML,则可以将 [Serializable] 全部省略,如果没有它,它将很好地序列化为 XML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多