How to fix Error 9459 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 9459 occurs when SQL Server’s native XML parser encounters malformed or non-well-formed XML data during a query that uses OPENXML, FOR XML, or XML data type methods. This typically stems from invalid characters, unclosed tags, mismatched namespaces, or truncated XML strings being passed into the parser. In SQL Server 2025 running on Windows Server 2025/Windows 11, this can also be triggered by encoding mismatches (UTF-8 vs UTF-16) when XML data is imported from external files or APIs.

Step-by-Step Resolution Guide

Step 1: Identify the Exact Line and Character Position

  • Run the failing query in SQL Server Management Studio (SSMS) and capture the full error message, including the line number referenced in “XML parsing: line %d”.
  • Use SELECT CAST(@xmlVariable AS NVARCHAR(MAX)) to dump the raw XML content to text for manual inspection.
  • Cross-reference the line number against the dumped text to locate the malformed tag or character.

Step 2: Validate the XML Structure Externally

  • Copy the problematic XML content into a validator tool (e.g., Visual Studio’s XML Editor or an online XML validator) to pinpoint syntax errors such as unclosed elements or invalid entity references.
  • Check for unescaped special characters like &, <, or > that must be encoded as &amp;, &lt;, or &gt;.
  • Verify the XML declaration (<?xml version="1.0" encoding="UTF-8"?>) matches the actual encoding of the source file.

Step 3: Correct Source Data or Import Process

  • If the XML originates from an external file, re-export it ensuring UTF-8 encoding without a BOM (Byte Order Mark), as BOM characters can cause parsing failures in SQL Server 2025.
  • Update the application or ETL process (SSIS package, PowerShell script, etc.) to sanitize XML output before insertion, using SELECT dbo.fn_EscapeXML(@rawInput) or similar custom sanitization functions.
  • If using OPENROWSET(BULK...) to load XML files, confirm the file path is accessible to the SQL Server service account under Windows Server 2025 security policies.

Step 4: Rebuild and Re-test the Query

  • Modify the XML column or variable with the corrected content and re-run the original FOR XML or OPENXML statement.
  • Check SQL Server error logs via EXEC sp_readerrorlog to confirm Error 9459 no longer appears after correction.

Alternative or Verification Steps

  • Verify the fix by running SELECT CAST(@xmlVariable AS XML) — if no error is thrown, the document is now well-formed.
  • If the error persists intermittently, enable XML schema validation using WITH XMLSCHEMA and bind a known-good XSD schema to catch structural issues before they reach production queries.