使用XmlSchemaValidator验证XmlElement,当xsi:nil=true时,使用专门的重载方法

来源:互联网 发布:中超球员数据库 编辑:程序博客网 时间:2024/06/06 06:51

当一个元素定义为可空nillable=true, 实际Xml节点xsi:nil=true, 验证时还是报内容无效,不能为空。

_validator.ValidateEndElement(null);

 

http://connect.microsoft.com/VisualStudio/feedback/details/97503/xmlschemavalidator-incorrectly-allows-xsi-nil-true-on-an-element-whose-nillable-is-false

 

Q: 

XmlSchemaValidator should not allow xsi:nil="true" on those xs:element whose nillable is false.

I tried some. 1) setting IsNil = true on XmlSchemaInfo which is being passed to ValidateElement() and so on. 2) call ValidateAttribute() with "nil" as localName and XmlSchema.InstanceNamespace as namespace URI.

A:

Thank you very much for your feedback. The issue you are running into is that nillabiliy is a constraint on the element not on the xsi:nill attribute itself. To validate the the element is appropriately set to nil or not you can use the overloaded ValidateElement method:
void ValidateElement(string localName, string namespaceURI, XmlSchemaInfo schemaInfo, string xsiType, string xsiNil, string xsiSchemaLocation, string xsiNoNamespaceSchemaLocation);

Validating the attribute xsi:nil is really just verifying whether one of the correct values of nil were provided.

Here is a background comment from a developer on this:
This is because, the value of the xsi attributes can even change the declaration we look up for the element. For example, xsi:type attribute can change the type of the element to a sub or super type. Even though xsi:nil does not change the element declaration, to be consistent, all xsi attribute processing is done via this overload and subsequent ValdiateAttribute calls on the xsi:attributes are ignored.

Thanks you again for this feedback. I will flag this bug for documentation to try to make the api clearer in this area. Thanks for your help!