Marsupilami
Marsupilami

Reputation: 23

C# data validation against XSD with fault location

I have classes generated from an xsd schema with xsd.exe. I don't have control over the schema. Reading, writing with XmlSerlializer and validation of the serialized data works just fine. I'd like to implement on-line error checking for my data what includes user input, based on the rules in the schema. Again I have no problem serializing and validating against, but then I see no easy way of tracking back the location of the fault, in which instance of which class did it occur. I found a comment mentioning that the reason for no XmlValidatingWriter exist is that the classes should already ensure schema compatibility, however this is not true for the xsd.exe generated classes. (structure and types are good but unique fields, patter matches etc. are not covered) There is a page about XmlSchemaValidator push-based validation but this seems super manual to me totally ignoring the fact that all of my classes are xml serializable.

I found similar questions but nobody seems to have this particular goal, nor I could find an answer that would lead me to a solution. I'm ok concluding this is not possible for some reason -as it looks to me now- but I'd like to understand the reason and get to know where my whole architecture went wrong.

Thank you.

Upvotes: 1

Views: 344

Answers (1)

Marsupilami
Marsupilami

Reputation: 23

Ok, here is what I ended up doing. I'm not proud of it.

  1. I have a base class that all of my xml nodes inherit from. I added a GUID property to it that is marked to be an xmlattribute and has the xmlignore attribute by default so that it doesn't take part in normal serialization / deserialization.
  2. When I'm about to serialize for validation I create an xmlattributesoverride to get rid of the xmlignore of the GUID property. The guid is going to be serialized to an xml attribute of each element.
  3. I create a new XDocument and serialize into it.
  4. I run XDocument.Validate using the schema I need to validate against.
  5. In the validation event handler I ignore all the errors that complain about the extra guid attribute.
  6. When I get a real validation error or warning I can find the actual object that got serialized into that particular element based on the guid.
  7. Profit.

Probably highly inefficient but for the size of the data I'm working with it's ok.

Upvotes: 1

Related Questions