Microsoft

Microsoft Docs

System.Xml.XmlFormatException Class

Namespace: System.Xml

Assembly: System.Xml.dll

Summary

Represents an error that occurs when an XML document does not conform to the XML standard or is otherwise malformed. This exception is thrown by the XML parser when it encounters a non‑recoverable error.

Syntax

public class XmlFormatException : XmlException

Constructors

ConstructorParametersDescription
XmlFormatException() None Initializes a new instance of the XmlFormatException class.
XmlFormatException(string message) message: The error message that explains the reason for the exception. Initializes a new instance with a custom error message.
XmlFormatException(string message, Exception innerException) message, innerException Initializes a new instance with a custom error message and a reference to the inner exception that is the cause.
XmlFormatException(string message, string sourceUri, int lineNumber, int linePosition) Message, source URI, line number, line position. Provides detailed location information for the error.

Properties

PropertyTypeDescription
LineNumber int Gets the line number where the error occurred.
LinePosition int Gets the column position within the line where the error occurred.
SourceUri string Gets the URI of the XML document that caused the exception.

Remarks

The XmlFormatException class inherits from XmlException. It adds additional context such as the exact line and position within the source XML. This information is useful for debugging malformed XML payloads.

Example

The following example demonstrates catching an XmlFormatException while loading an XML document.

using System;
using System.Xml;

class Demo
{
    static void Main()
    {
        string xml = @"<root>
                         <item>Value</item>
                         <unclosedTag>Oops
                       </root>";

        try
        {
            var doc = new XmlDocument();
            doc.LoadXml(xml);
        }
        catch (XmlFormatException ex)
        {
            Console.WriteLine($"Format error at line {ex.LineNumber}, position {ex.LinePosition}:");
            Console.WriteLine(ex.Message);
        }
    }
}

See Also

On This Page