简体   繁体   中英

Skip attributes in XML Deserialization

Currently I use the following approach to deserialize a RESTful XML return:

[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;
   }
}

This is the XML return:

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

If I don't want to grab the ItemId in public class Part it unfortunately does not work to simply remove these two lines from public class Part :

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

1) What is the correct approach to skip the ItemId attribute?
2) What would be the the easiest way to access Cost only and omit everything else? (I didn't add it to public class Part in my example though)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM