Reputation: 6730
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.
Upvotes: 2
Views: 1837
Reputation: 45771
Without seeing the definition of MyClass
and 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:
<AnotherTag>
<MyTag>
</AnotherTag> <--- This should be </MyTag>
</MyTag> <--- This should be </AnotherTag>
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 InvalidOperationException
is raised because the XML isn't XML, the UnknownElement
event is raised because there's an element in the XML that is unexpected, though the XML is otherwise valid.
Upvotes: 1
Reputation: 161783
The two events you're handling have nothing to do with errors in the XML document structure.
I'll try to help you with the specific problem once you post the specific exception. You might even need to post the XML.
From the looks of the partial exception you posted, it appears that your document is invalid XML (mismatched tags). There is no way to detect this short of catching an exception.
Upvotes: 0