1

in the xsd schema I have defined an attribute Id as

<xs:attribute name="ID" type="xs:nonNegativeInteger" use="required"/>

However, the validation of xml towards the xsd schema passes even if ID is set to a value greater then UInt32.MaxValue.

My deserialization code looks as follows:

var ser = new XmlSerializer(typeof(MyClass));
var settings = new XmlReaderSettings();
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessIdentityConstraints |    XmlSchemaValidationFlags.AllowXmlAttributes;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(_schemaNs, _schemaFileName);

var tReader = XmlReader.Create(filename, settings);
try
{
      var obj = ser.Deserialize(tReader) as MyClass;
}
catch(Excetion e)
{/*Process Validation exception.*/}

where the corresponding variables are defined above.

In the definition of MyClass I have:

    private uint idField;
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public uint ID
    {

        get
        {               
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

Now, I'd like the XmlSerializer to throw an exception if the value of ID is set to a too big number. The first idea, which came to my mind is to set the type of ID field in MyClass to string and perform validation by myself. However it seems that there is a more elegant way to do this.

Vahagn
  • 386
  • 2
  • 21

2 Answers2

1

I suggest to encode the logic for filtering undesired values not into the deserialization, but into the setter itself, which can be done as follows.

private uint idField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public uint ID
{
    get
    {               
        return this.idField;
    }
    set
    {
        int SOME_BOUND = 10000;
        if (value > SOME_BOUND)
        {
            throw new ApplicationException();
        }
        this.idField = value;
    }
}

The class ApplicationException is documented here. The ArgumentOurOfBoundsException might also be suitable.

Codor
  • 17,447
  • 9
  • 29
  • 56
1

Probably you can specify it in the XSD Schema this way:

<xs:attribute name="ID" use="required">
    <xs:simpleType>
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0"/>
            <xs:maxInclusive value="4294967295"/>
        </xs:restriction>
    </xs:simpleType>
</xs:attribute>

The following SO post might be helpful too.

Community
  • 1
  • 1
Ramanagom
  • 329
  • 2
  • 8