【问题标题】:Change the namespace of DataContract更改 DataContract 的命名空间
【发布时间】:2014-07-18 12:44:25
【问题描述】:

我必须从其他 Windows 服务保存的数据库中检索 xml 数据。

这里是存储在我的数据库中的 XML 数据:

<ArrayOfDescription.Traduction xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/OtherNamespace">
   <Description.Traduction>
      <Description>Contact ouvert</Description>
      <Label>Ouvert</Label>
      <LcId>12</LcId>
   </Description.Traduction>
   <Description.Traduction>
      <Description>Contact open</Description>
      <Label>Open</Label>
      <LcId>9</LcId>
   </Description.Traduction>
</ArrayOfDescription.Traduction>

我的类名是 Description,我的字符串属性名是 TradBlob。检索存储在我的数据库中的数据没有问题。然后我定义了一个描述的部分类来帮助我进行反序列化。

public partial class Description
{
     [DataContract(Name = "Description.Traduction", Namespace = "http://schemas.datacontract.org/2004/07/OtherNamespace")]
     public class Traduction
     {
        public string Description { get; set; }
        public string Label { get; set; }
        public int LcId { get; set; }
     }
}

然后在UI端,我可以写:

LabelTrad = SerializerHelper.Deserialize<List<Description.Traduction>>(TradBlob).Single(x=>x.LcId == CurrentLcId).Label

这里是我的反序列化方法:

public static T Deserialize<T>(string xml)
{
  if (string.IsNullOrEmpty(xml)) return default(T);

  try
  {
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
      var serializer = new DataContractSerializer(typeof(T));
      T theObject = (T)serializer.ReadObject(stream);
      return theObject;
    }
  }
  catch (SerializationException e)
  {
    // La déserialisation s'est mal passée, on retourne null
    return default(T);
  }
}

我的问题是反序列化没有按预期工作。标签为空。

你知道哪里出了问题吗?

注意:我无法在 Description 类中修改 Traduction 类的创建。

【问题讨论】:

  • 给我们看SerializeHelper.Deserialize的代码
  • 我在问题里面添加了反序列化方法。
  • 您是否尝试在SerializationException 中设置断点并查看是否抛出任何异常?
  • 不抛出异常。这就是困扰我的原因
  • 尝试删除对Single的调用,看看该列表是否真的返回

标签: c# xml namespaces deserialization datacontract


【解决方案1】:

我忘记在 Description、Label 和 LcId 属性中添加 DataMember 注释。 谢谢大家

【讨论】:

    猜你喜欢
    • 2011-11-16
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多