简体   繁体   English

序列化为XML时如何有选择地排除类成员

[英]How to Optionally exclude a class member when serializing to XML

I just took over a fairly large project. 我刚刚接手了一个相当大的项目。 One of my tasks is to modify the code that gets rate quotes from FedEx. 我的任务之一是修改从FedEx获取报价的代码。 Currently, in order to get a set of rate quotes for a shipment that includes quotes for each "ServiceType" (Ground, 2-day, overnight, etc.) the code makes one call for each type. 当前,为了获得包括每个“ ServiceType”(地面,2天,整夜等)报价的货件的一组报价,代码对每种类型进行一次调用。 FedEx offers a web service that is used to get this information. 联邦快递提供了用于获取此信息的Web服务。 After doing a little research, it looks like this web service can return multiple ServiceType quotes with a single round-trip. 经过一些研究后,看起来该Web服务可以通过一次往返返回多个ServiceType引号。 To do this, I'm supposed to "leave the service type out of the request." 为此,我应该“将服务类型排除在请求之外”。 ( Here's the question that pointed me in that direction .) 以下是向我指出该问题的问题 。)

So I know that I can exclude the service type property from the serialization by decorating the property with, [System.Xml.Serialization.XmlIgnoreAttribute()] . 因此,我知道可以通过使用[System.Xml.Serialization.XmlIgnoreAttribute()]装饰属性来从序列化中排除服务类型属性。 But how can I do that only when I want results for all the ServiceType values and still be able to pass a single service type for the cases where I know what shipping method the user wants? 但是,只有在我希望获得所有ServiceType值的结果并且仍然能够在我知道用户想要哪种运输方式的情况下仍能够传递单个服务类型时,才可以这样做吗?

EDIT: FedEx's documentation indicates that this field is optional. 编辑:FedEx的文档指示此字段是可选的。 Some basic testing shows that excluding it from the request with the XmlIgnoreAttribute does return data for multiple ServiceTypes. 一些基本测试表明,使用XmlIgnoreAttribute从请求中排除它确实会返回多个ServiceType的数据。

If you implement a public bool ShouldSerializeXXX() function alongside the XXX property being serialized, XmlSerializer will ignore the corresponding XXX property when the function returns false . 如果在要序列化的XXX属性旁边实现一个public bool ShouldSerializeXXX()函数,则当该函数返回false时,XmlSerializer将忽略相应的XXX属性。 You'll have to have some basis for setting this (maybe the XXX property can be null? or you can grab some other state to make the decision.) 您必须具有一定的设置基础(也许XXX属性可以为null?或者可以使用其他状态来做出决定)。

So, something along these lines: 因此,遵循以下原则:

public class MyClass
{
    public ServiceType? ServiceType { get; set; }
    public bool ShouldSerializeServiceType() { return ServiceType.HasValue; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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