DataContractSerializer区分大小写

时间:2014-12-19 10:23:27

标签: c# xml deserialization

我需要将原始xml反序列化为特定对象。但是,当涉及布尔类型和枚举类型时,我遇到了问题,因为区分大小写完好无损。

public MyObjectTypeDeserializeMethod(string rawXML)
{   
    DataContractSerializer serializer = new DataContractSerializer(typeof(MyObjectType));   
    MyObjectType tempMyObject = null;

    try
    {
        // Use Memory Stream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // Use Stream Writer
            using (StreamWriter streamWriter = new StreamWriter(memoryStream))
            {
                // Write and Flush
                streamWriter.Write(rawXML);
                streamWriter.Flush();

                // Read
                memoryStream.Position = 0;
                tempMyObject = (MyObjectType)serializer.ReadObject(memoryStream);
            }
        }
    }
    catch (Exception e)
    {
         throw e;
    }

    return tempMyObject;
}

public class MyObjectType
{
    public bool boolValue {get; set;}
    public MyEnumType enumValue {get; set;}
}

如果原始XML包含

<boolValue>true</boolValue>

它工作正常。但是,只要值与前一个值不同,它就会抛出异常,例如

<boolValue>True</boolValue>

为了允许从原始XML传递不区分大小写的布尔值和枚举值,如何解决此问题?

2 个答案:

答案 0 :(得分:1)

xml specification xml定义为区分大小写,布尔值定义为(注释案例)文字true和{{1 }}。 false做得对。如果值为DataContractSerializer,那么它不是xml布尔值,应该被视为True

答案 1 :(得分:1)

有很多方法可以解决这个问题。这种方法很简单:

public class MyObjectType
{
  [XmlIgnore] public bool BoolValue;  // this is not mapping directly from the xml

  [XmlElement("boolValue")]
  public string BoolInternalValue  // this is mapping directly from the xml and assign the value to the BoolValue property
  {
      get { return BoolValue.ToString(); }
      set
      {
          bool.TryParse(value, out BoolValue);
      }
  }
  ...

我使用XmlSerializer反序列化xml:

    public static T Deserialize<T>(string xmlContent)
    {
        T result;
        var xmlSerializer = new XmlSerializer(typeof(T));
        using (TextReader textReader = new StringReader(xmlContent))
        {
            result = ((T)xmlSerializer.Deserialize(textReader));
        }
        return result;
    }