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 World Wide Web Consortium (W3C) Recommendation.
Note
In the .NET Framework version 2.0, the recommended practice is to create XmlReader instances using the XmlReaderSettings class and the Create method. This allows you to take full advantage of all the new features introduced in the .NET Framework 2.0. For more information, see Creating XML Readers.
Example
The following code example shows the XmlException class returning a LineNumber, LinePosition, and a source URI 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("Exception source URI: (" + e.SourceURI + ")")
Console.WriteLine(("XmlReader Line, pos: (" & tr.LineNumber & "," & tr.LinePosition & ")"))
End Try
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("Exception source URI: (" + e.SourceURI + ")");
Console.WriteLine("XmlReader Line, pos: (" + tr.LineNumber + "," + tr.LinePosition + ")");
}
See Also
Reference
Concepts
Reading XML Data with XmlTextReader
Full Content Reads Using Character Streams