跳过XML反序列化中的属性

时间:2017-03-23 19:08:11

标签: c# xml

目前,我使用以下方法反序列化RESTful XML返回:

[DataContract(Name = "Part", Namespace = "")]
public class Part
{
   [DataMember(Order = 1)]
   public string ItemId { get; set; }
   [DataMember(Order = 2)]
   public string ItemDescription { get; set; }
   [DataMember(Order = 3)]
   public string Weight { get; set; }
}

public bool GetPartInformation(string itemId)
{
   var URL = "...some URL...";
   client.BaseAddress = new Uri(URL);

   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

   HttpResponseMessage response = client.GetAsync(urlParameters).Result;
   if (response.IsSuccessStatusCode)
   {
       Part part = response.Content.ReadAsAsync<Part>().Result;

       Console.WriteLine("ItemId: {0}", part.ItemId);
       Console.WriteLine("Description: {0}", part.ItemDescription);
       Console.WriteLine("Weight: {0}", part.Weight);

       return true;
   }
   else
   {
       Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
       return false;
   }
}

这是XML返回:

<Part>  
    <ItemId>12345</ItemId>  
    <ItemDescription>Item Description</ItemDescription>  
    <Weight>0.5</Weight>  
    <Cost>190.59</Cost>  
</Part>

如果我不想抓取public class Part中的ItemId,那么遗憾的是,它无法从public class Part中删除这两行:

[DataMember(Order = 1)]
public string ItemId { get; set; }

1)跳过ItemId属性的正确方法是什么?
2)仅访问Cost并省略其他所有内容的最简单方法是什么? (我的例子中没有将它添加到public class Part

1 个答案:

答案 0 :(得分:1)

如果从要忽略的属性中删除[DataMember]属性,则将从反序列化中排除所有此类属性。