0

I have a utility that converts an xml file to a class object:

    public static T CreateClassFromXml<T>(string fileName, string root) where T : class
    {
        fileName.ThrowNullOrEmpty("fileName");

        File.Exists(fileName).ThrowFalse(string.Format("File '{0}' could not be found", fileName));

        var serializer = new XmlSerializer(typeof(T), new XmlRootAttribute() { ElementName = root });

        using (var reader = XmlReader.Create(fileName))
        {
            return (T)serializer.Deserialize(reader);
        }
    }

The utility reads the xml and creates a class T. Using the above code is there any way I can validate the created class other than writing a wrapper class around it? I need to ensure that data is populated for all mandatory fields.

dotnetnoob
  • 10,783
  • 20
  • 57
  • 103
  • You can validate `XML` using `XSD`. – Hamlet Hakobyan Oct 21 '13 at 15:17
  • You could mark the mandatory components with attributes (System.ComponentModel.DataAnnotations namespace comes to mind). Then, perfom validation of your object : http://stackoverflow.com/a/7665862/1236044 – jbl Oct 21 '13 at 15:27

1 Answers1

0

There are no built in facilities in XmlSerializer to do this. You can do it yourself with reflection. Since XmlSerializer loads just the public properties and fields, you can iterate over all public properties and fields of the class and make sure they all hold data. You'll have to decide how to handle value types (int, DateTime, etc...) because it's not obvious when the have been loaded or not. You will also have to dive in recursively into reference types.

If you need to mark just specific properties\fields as mandatory, you can add your own attribute and decorate the class members with it. In runtime, you will only process properties which have the attribute set.

In short, unless you need a generic mechanism for many different scenarios, better do it manually for the properties you have to validate.

Alon Catz
  • 2,417
  • 1
  • 19
  • 23
  • Define the value types int, double etc. as nullable and check after deserialization if there is any null value. I dont remember if the ondeserialization attributes apply to XML... I thing they dont but you could have a look. – GuillaumeA Oct 21 '13 at 15:39