Elements with restrictions can't be set to null to remove

Jun 23, 2011 at 10:17 PM

The exception occurs during datatype.ChangeType (where value=null and DataType.ValueType~=System.String):

The schema element in question looks like this:

	<xs:element name="MyElement" type="T_someType" minOccurs="0"/>
	<xs:simpleType name="T_someType">
		<xs:restriction base="xs:string">
			<xs:enumeration value="value1"/>
			<xs:enumeration value="value2"/>
			<xs:enumeration value="value3"/>

The behavior I want is being able to either set the element to one of the three string values, or null in order to remove it (which is the behavior of elements without restrictions).  But because of the restriction, the following code

_parent.MyElement = null;

throws the exception:

Xml.Schema.Linq.LinqToXsdException was unhandled by user code
  Message=Failed to set value on the property "MyElement". Possible reason: Value cannot be null.
Parameter name: value
       at Xml.Schema.Linq.XTypedElement.SetElementWithValidation(XName name, Object value, String propertyName, SimpleTypeValidator typeDef) in ...\branches\2.0\XObjects\Src\API\XObjectsSimpleType.cs:line 54

Any thoughts? (other than removing the restriction)

Jun 23, 2011 at 11:12 PM

Got it.  Instead of setting the element to null, I now just bypass validating by removing it myself via the Untyped property. 

	_parent.MyElement = null;
	_parent.Untyped.SetElementValue(XName.Get("MyElement"), null);