C# - XML将复杂类序列化为其原始类型

时间:2013-04-26 02:26:01

标签: c# xml-serialization

是否可以采用复杂的类“A”,它表示具有附加信息的基本类型 - 例如该基元的有效值,包括“B”中的“A”实例,以及XML序列化“B” “A”只作为原始类型出现?

Class A<T> {
  T obj;
  Static  ValidValue<T>[] validValues;
}

Class B {
  A<int> intVal;
  A<string> stringVal;
}

所需的输出只是原语。 ValidValues将用于在反序列化后验证数据:

  <B>
    <A>1</A>
    <A>example</A>
  </B>

3 个答案:

答案 0 :(得分:2)

您是否尝试过使用房产?

public class B {
  private A<int> intVal;
  public int IntVal{
    get{
      return intVal.obj;
    }
    set{
      intVal.obj = value;
    }
  }

  // same for stringval
}

据我所知,xmlserializer只会序列化公共属性。所以它应该有用。

我可能会误解你的要求。

答案 1 :(得分:1)

使用DataContracts很容易。

您只需要在类上放置[DataContract]属性,然后仅使用[DataMember]属性装饰 要序列化的字段或属性。您可以通过这种方式序列化私有字段。

See here for how to serialize such a decorated class

这是选择加入,即只有您使用[DataMember]装饰的项目才会被序列化。

例如(from the MSDN sample here):

[DataContract]
public class Person
{
    // This member is serialized.
    [DataMember]
    internal string FullName;

    // This is serialized even though it is private.
    [DataMember]
    private int Age;

    // This is not serialized because the DataMemberAttribute 
    // has not been applied.
    private string MailingAddress;

    // This is not serialized, but the property is.
    private string telephoneNumberValue;

    [DataMember]
    public string TelephoneNumber
    {
        get { return telephoneNumberValue; }
        set { telephoneNumberValue = value; }
    }
}

答案 2 :(得分:0)

您可以使用自定义序列化来控制序列化的变量。然后,您可以将任何值发送到序列化对象。

请参阅http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx

相关问题