Do XML parsers tell the difference between xsi:nil=“true” and omitted elements?

自古美人都是妖i 提交于 2019-12-05 11:14:29

XML parsers (e.g. XmlReader, XmlDocument, XDocument) don't treat xsi:nil specially - you still see the element in the stream/document.

XmlSerializer does handle xsi:nil: within that context it means the same thing as an omitted node; you can make WCF serialize using XmlSerializer by marking your DataContracts using XmlSerializerFormatterAttribute.

DataContractSerializer does use the attribute: however I am not sure what all the rules are for it to use them (one case is circular references) - it is much more likely to omit elements. I don't think you should pass xsi:nil to DataContractSerializer unless it uses it in that case - as DataContractSerializer is designed around assumptions to improve de/serialization performance.

From the spec it looks like it was originally designed to work like the JavaScript null and undefined - where null (xsi:nil) is a valid value and undefined (omitted) is the entire non-existence of a value; especially with complex types - you can provide the element but omit it's content (even if the content is required according to the schema).

In general I would avoid it. It's non-intuitive - I don't think I have seen a REST/SOAP API out there that uses it (except InfoPath which uses it exclusively); most just use null = undefined. The xmlns declaration and usage of it also eat a few extra valuable bytes.

Bonus Marks: If you make an element optional and it isn't nullable (e.g. xsd:int) the C# generator provides a <Name>Specified property - you can add your own properties like this. This would allow you to differentiate between xsi:nil and omittance (nil when specified and null, omitted when not specified). However, this only works with XmlSerializer.

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