Exception Handling Using XmlException in XmlTextReader

The XmlException class is used with the XmlTextReader class to catch errors in data when it finds syntax errors during parsing. The errors that are caught are a result of problems with the way the data is structured, as data should be structured according to the rules defined in the W3C recommendation.

The following code sample shows the XmlException class returning a LineNumber and LinePosition of an error in the LineNumber.xml document, assuming that the XML in the LineNumber.xml document is not well-formed.

Dim tr As New XmlTextReader("LineNumber.xml")
Dim r As New XmlValidatingReader(tr)
r.ValidationType = ValidationType.None
Try
   While r.Read()
   End While
Catch e As XmlException
   Console.WriteLine(e.Message)
   Console.WriteLine(("Exception object Line, pos: (" & e.LineNumber & "," & e.LinePosition & ")"))
   Console.WriteLine(("XmlReader Line, pos: (" & tr.LineNumber & "," & tr.LinePosition & ")"))
End Try

[C#]
XmlTextReader tr = new XmlTextReader("LineNumber.xml");
XmlValidatingReader r = new XmlValidatingReader(tr);
r.ValidationType = ValidationType.None;
try {
   while(r.Read());
}
catch(XmlException e) {
   Console.WriteLine(e.Message);
   Console.WriteLine("Exception object Line, pos: (" + e.LineNumber + "," + e.LinePosition  + ")");
   Console.WriteLine("XmlReader Line, pos: (" + tr.LineNumber + "," + tr.LinePosition  + ")");
}

For more information, see XmlException Members.

See Also

Reading XML with the XmlReader | Full Content Reads using Character Streams | Document Type Declaration Information | Handling White Space with XmlTextReader | Attribute Value Normalization | XmlReader Class | XmlReader Members | XmlTextReader Class | XmlTextReader Members