Declare [XmlElement(IsNullable = true)] at class level

故事扮演 提交于 2019-12-23 19:36:36

问题


Is there a way to declare [XmlElement(IsNullable = true)] at class level so that all properties in the class will be XML serialized, even if they are null?

e.g.

public BankAccount BankAccount { get; set; }

Should result in <BankAccount xsi:nil="true" />, rather than the default missing element.

I tried this but the compiler (correctly) states that the attribute is not valid for class declarations.

The reason for this is that I don't want to have to specify this for all properties.


Edit: This is the serialization method I am using:

        var serializer = new XmlSerializer(FormType);
        var stream = new MemoryStream();

        serializer.Serialize(stream, form);

回答1:


Unfortunately you have to be explicit when annotating your class for XML serialization. Each property must be annotated with its own XmlElement attribute unless you want a default behaviour.




回答2:


see this thread: Setting the [XmlElement(IsNullable = true)] attribute at run time



来源:https://stackoverflow.com/questions/9187047/declare-xmlelementisnullable-true-at-class-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!