How to generate xsi:nil element with attributes?
I have a WCF client that needs to generate a request containing this XML fragment :
<reason xsi:nil="true" nullFlavor="NA" typeCode="RSON" />
The schema is determined by the server and isn't under my control. The generated proxy code has a class for开发者_开发问答 the reason element containing (among other things) properties nullFlavor
and typeCode
. The proxy uses the XmlSerializer.
How can I generate such a fragment? The XmlSerializer emits the xsi:nil
attribute only if the corresponding member is null. And if it's null, it can't very well have properties that will be emitted as attributes!
BTW, the fragment is legal according to the XML Schema Instance spec, which says a nil element cannot contain any child elements or inner text, but may contain attributes.
Here is the solution I used for those still struggling with this issue. It is a bit of a hack but it works. Turn off nillable and add and attribute as below
[XmlAttributeAttribute( AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance" )]
public bool NillAtt
{
get
{
return this.nillAtt;
}
set
{
nillAtt = value;
}
}
This is a known limitation of the XmlSerializer. You may be able to get around it with some clever use of the IXmlSerializable interface and emitting the XML manually - unfortunately there isn't a clean solution that I know of.
精彩评论