I have an XmlSerializer object, and I have added 2 event handlers to the UnknownElement and UnknownAttribute events, as below:
XmlSerializer xs = new XmlSerialiser(typeof(MyClass));
xs.UnknownAttribute += new XmlAttributeEventHandler(xs_UnknownAttribute);
xs.UnknownElement += new XmlElementEventHandler(xs_UnknownAttribute);
Each of these event handlers basically do the same thing, they print out the node name or the attribute name causing the issue.
But for some reason, an InvalidOperationException is getting thrown saying there is an error in the xml document with . I thought these errors would be caught by my events?
Update
The exceptions are:
The exception is: Unhandled Exception: System.InvalidOperationException: There is an error in XML document (5, 110).
There is an InnerException of type XmlException, which states The ‘MyTag’ start tag on line 5 does not match the end tag of ‘AnotherTag’. Line 5, position 110.
Without seeing the definition of
MyClassand the XML that you’re trying to read in, it’s hard to give a definitive answer. That said, the text of the exception is quite obvious, the XML markup is malformed, rather than containing an unknown element or attribute, for example:UnknownAttribute/UnknownElement handlers won’t capture this because the structure of the XML is fundementally wrong. These events can’t be called until the XML document has been sucessfully parsed into a tree of nodes, child nodes, attributes and so on.
Just to further explain the bit about UnknownAttribute/UnknownElement; if your class/XML was only allowed to contain elements called Field1 and Field2 then you’d find the UnknownElement event raised if you had an element called Field3 in your XML. The
InvalidOperationExceptionis raised because the XML isn’t XML, theUnknownElementevent is raised because there’s an element in the XML that is unexpected, though the XML is otherwise valid.