Inferensys

Prompt

XML Parser Error Recovery Prompt Template

A practical prompt playbook for using XML Parser Error Recovery Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the XML Parser Error Recovery Prompt Template.

This prompt is for integration engineers and backend developers who receive malformed XML from external systems—upstream partners, legacy services, or user-submitted documents—and need a structured, actionable error report instead of a raw parser exception. The job-to-be-done is not just to identify that an error occurred, but to produce a machine-readable diagnostic with line numbers, recovery suggestions, and a best-effort repaired XML document that can be fed into a downstream validation or retry pipeline. The ideal user is someone who owns an ingestion pipeline and needs to decide programmatically whether to auto-repair, quarantine, or reject a payload based on the severity and type of malformation.

Use this prompt when you have already attempted a strict XML parse and caught a failure, and you now need the model to act as a structured recovery assistant. It is appropriate for common malformation patterns such as unclosed tags, mismatched case in element names, missing namespace declarations, illegal characters, incorrect nesting, or duplicate attributes. It is not appropriate for binary data corruption, encoding-level byte errors, or schema-level semantic violations where the XML is well-formed but logically invalid against an XSD. In those cases, a separate schema validation prompt or a binary repair tool is the correct next step. Do not use this prompt as a replacement for a streaming XML parser or for real-time, high-throughput ingestion where latency and cost make a model call impractical.

Before invoking this prompt, ensure you have captured the raw malformed XML string, the parser error message, and the line and column numbers if available. The prompt template expects these as inputs and uses them to ground the recovery attempt. The output is a structured report, not a conversational explanation, so wire this into an application harness that can parse the JSON response and route the repaired XML to a schema validator. If the repair confidence is low or the malformation involves security-relevant structures like XML signatures or encryption, escalate for human review rather than auto-accepting the repaired document. The next section provides the copy-ready template you can adapt into your error-recovery pipeline.

PRACTICAL GUARDRAILS

Use Case Fit

Where the XML Parser Error Recovery prompt works and where it introduces unacceptable risk.

01

Good Fit: Malformed External Feeds

Use when: You ingest XML from third-party systems with known encoding errors, unescaped characters, or missing closing tags. Guardrail: The prompt should produce a structured error report and a best-effort repair, but always log the original raw payload before any AI repair attempt.

02

Bad Fit: Security-Critical Payloads

Avoid when: The XML contains SAML assertions, signed documents, or authentication tokens. Guardrail: AI repair can invalidate digital signatures or canonicalization. Route these to deterministic schema validators and reject malformed security payloads outright instead of repairing them.

03

Required Input: Raw Malformed String

What to watch: The model needs the exact byte sequence that caused the parser to fail, not a sanitized copy. Guardrail: Pass the raw input as a code-fenced string with the original encoding declared. If the input contains null bytes or control characters, use base64 encoding with an explicit decode instruction in the prompt.

04

Required Input: Parser Error Context

What to watch: The model performs better when it sees the exact error message, line number, and column position from the failing parser. Guardrail: Include the parser's error output verbatim as a separate field in the prompt. Do not summarize or truncate the error message.

05

Operational Risk: Silent Data Corruption

What to watch: The model may 'repair' XML by dropping elements it cannot parse, changing data values, or reordering fields to make the document valid. Guardrail: Require a structured diff in the output showing every change made. Run automated comparison between the original and repaired document before ingestion.

06

Operational Risk: Repair Loop Exhaustion

What to watch: Severely corrupted XML may require multiple repair passes, consuming tokens and latency budget without converging. Guardrail: Set a maximum of 2 repair attempts. If the output still fails validation, escalate to a human operator with the original payload, error log, and both repair attempts attached.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for diagnosing and repairing malformed XML from external systems.

This prompt template is designed to be dropped into your integration pipeline whenever an upstream system delivers XML that fails standard parsing. It instructs the model to act as a strict XML diagnostician, producing a structured error report and a best-effort repaired document. The template uses square-bracket placeholders for all dynamic inputs, allowing you to inject the raw payload, known schema references, and risk tolerance before each call.

text
You are an XML error recovery specialist. Your task is to analyze a malformed XML document, produce a structured diagnostic report, and generate a best-effort repaired version.

## INPUT
[RAW_XML_PAYLOAD]

## CONTEXT
- Known Schema or DTD: [SCHEMA_REFERENCE or "None provided"]
- Expected Root Element: [ROOT_ELEMENT_NAME or "Unknown"]
- Downstream Parser: [PARSER_NAME_AND_VERSION, e.g., "lxml 4.9.3"]
- Risk Level: [RISK_LEVEL: "conservative" | "moderate" | "aggressive"]
  - conservative: Only fix unambiguous, well-defined errors. Flag all others for human review.
  - moderate: Apply common heuristics for missing quotes, unescaped entities, and mismatched tags.
  - aggressive: Attempt to reconstruct the document structure even with severe corruption. Mark all changes.

## OUTPUT_SCHEMA
Return a single JSON object with the following structure:
{
  "parse_success": boolean,
  "error_report": {
    "total_errors": integer,
    "errors": [
      {
        "line": integer or null,
        "column": integer or null,
        "error_code": string,
        "severity": "fatal" | "error" | "warning",
        "description": string,
        "raw_snippet": string
      }
    ]
  },
  "recovery_applied": boolean,
  "repaired_xml": string or null,
  "changes_summary": [
    {
      "change_type": "tag_fix" | "quote_fix" | "entity_escape" | "encoding_fix" | "structural_reconstruction" | "other",
      "location_hint": string,
      "original": string,
      "replacement": string,
      "confidence": "high" | "medium" | "low"
    }
  ],
  "human_review_required": boolean,
  "review_reasons": [string]
}

## CONSTRAINTS
- Do not invent content to fill gaps. If a section is irrecoverable, omit it and flag it.
- Preserve all namespace declarations and prefixes exactly as found, unless they are the source of the error.
- If [RISK_LEVEL] is "conservative" and any error has severity "fatal", set "recovery_applied" to false and "repaired_xml" to null.
- Always set "human_review_required" to true if any change has "confidence" of "low".
- If [SCHEMA_REFERENCE] is provided, validate the repaired XML against it and report any remaining schema violations in the error_report.
- Do not wrap the JSON output in markdown code fences.

To adapt this template for your environment, replace the placeholders with your actual runtime values. The [RISK_LEVEL] parameter is the most critical tuning knob: start with "conservative" in production and only move to "moderate" or "aggressive" after reviewing failure patterns over several weeks. If you have an XSD or DTD, always provide it in [SCHEMA_REFERENCE]—this enables the model to catch structural errors that basic well-formedness checks miss. For high-stakes integrations (payments, healthcare, identity), always require human review when "human_review_required" is true, and log the full changes_summary for audit trails.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the XML Parser Error Recovery Prompt Template. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed and safe before model invocation.

PlaceholderPurposeExampleValidation Notes

[MALFORMED_XML]

The raw, malformed XML string that needs error recovery and repair

<root><item>Broken<item></root>

Must be a non-empty string. Validate that the input is intended as XML, not binary data or plain text. Check for null bytes and encoding mismatches before passing to the model.

[PARSER_ERROR_LOG]

The raw error output from the XML parser that attempted to parse [MALFORMED_XML]

error on line 3: mismatched tag at column 14

Must be a non-empty string. If the parser produced no errors, this prompt is not needed. Validate that the error log corresponds to the provided [MALFORMED_XML] input to prevent hallucinated repairs on valid documents.

[PARSER_NAME]

The name and version of the XML parser that produced the error log

lxml 4.9.3

Must be a string identifying a real XML parser. Used to interpret parser-specific error messages. If unknown, use 'generic XML parser'. Do not invent parser versions.

[EXPECTED_ROOT_ELEMENT]

The expected root element name for the repaired document, if known

catalog

Optional. If provided, must be a valid XML element name with no namespace prefix unless [EXPECTED_NAMESPACE] is also provided. Null allowed when root element is unknown.

[EXPECTED_NAMESPACE]

The expected XML namespace URI for the document, if known

Optional. If provided, must be a valid URI string. Used to guide namespace-aware repair. Null allowed when namespace is unknown or not applicable.

[RECOVERY_STRATEGY]

The preferred recovery approach: conservative, aggressive, or best-effort

conservative

Must be one of: 'conservative' (drop unrecoverable sections), 'aggressive' (attempt structural inference), or 'best-effort' (balance both). Defaults to 'best-effort' if not specified. Invalid values should cause a pre-flight rejection.

[OUTPUT_SCHEMA]

The JSON schema that the error report and repaired XML must conform to

{"type": "object", "required": ["errors", "repairs", "repaired_xml"]}

Must be a valid JSON Schema object. Validate parseability before prompt assembly. Schema must require at minimum: errors array, repairs array, and repaired_xml string. Reject schemas that allow empty error arrays when [PARSER_ERROR_LOG] is non-empty.

[MAX_REPAIR_ATTEMPTS]

The maximum number of repair iterations before returning partial results

3

Must be a positive integer between 1 and 10. Used to bound repair loops. Values outside this range should be clamped or rejected. Defaults to 3 if not provided.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the XML Parser Error Recovery prompt into an application or automated pipeline.

This prompt is designed to be the core of a repair microservice or a step in an ETL pipeline. It receives malformed XML, a raw parser error, and a target schema, and returns a structured error report alongside a best-effort repaired document. The harness must treat the model as a fallible repair agent, not an oracle. The primary integration point is an API endpoint or a queue consumer that catches XMLSyntaxError or SAXParseException from a standard parser like lxml or javax.xml.parsers, captures the exact error message and line number, and forwards them to the model with the original raw string. The model's output must be validated before the repaired XML is allowed to proceed downstream.

Wiring the pipeline: The application should first attempt a strict parse. On failure, capture the exception object's lineno, offset, and msg fields. Construct the prompt with [MALFORMED_XML] set to the original byte string, [PARSER_ERROR] set to the full exception text, and [TARGET_SCHEMA] set to the expected XSD or a prose description of required elements. The model's JSON output must be parsed and validated: check that repair_report.error_line matches the captured lineno, that repaired_xml is not identical to the input, and that repaired_xml parses successfully with the same strict parser. If the repaired document fails to parse, the harness should retry once by feeding the new parser error back into the prompt as [PARSER_ERROR] with a note that this is a second attempt. If the second attempt also fails, the harness must log the full failure context and route the document to a human review queue rather than silently dropping it.

Model choice and tool use: This task requires strong code and structured data reasoning. Use a model with a large context window and strong JSON mode support, such as gpt-4o or claude-3.5-sonnet. Do not provide the model with a code execution tool for this task; the repair must be a direct text transformation. The harness should, however, use a deterministic post-processing tool to canonicalize the repaired XML (e.g., xmllint --format) before comparing it to the original. For high-throughput pipelines, implement a local cache keyed on a hash of [MALFORMED_XML] + [PARSER_ERROR] to avoid re-prompting for identical failures. Log every repair attempt with the input hash, model version, retry count, and final parse success/failure for observability.

Validation and evals before production: Build a golden test set of 20-30 real-world malformed XML examples: unclosed tags, illegal characters, mismatched case, missing namespaces, and encoding issues. For each, store the expected minimum repair (the document must parse and contain all original text content). Run the harness against this set and measure repair success rate (strict parse passes) and content preservation rate (all original text nodes present in the repaired document). Set a gate: if repair success rate drops below 85% after a prompt or model change, block the release. Additionally, run the prompt against well-formed XML to ensure it does not "repair" valid documents. The harness must reject any repaired document that introduces new elements not present in the original malformed input, as this indicates hallucination.

What to avoid: Do not use the repaired XML for security-critical operations like SAML assertion processing or XML signature verification without human review. The model can fix structure but cannot guarantee semantic integrity. Never expose the raw malformed XML to end users without sanitization, as it may contain injection payloads. Finally, do not wire this prompt directly into a synchronous user-facing flow; the retry loop and model latency make it unsuitable for real-time interactions. It belongs in asynchronous document ingestion pipelines where a 2-5 second repair delay is acceptable.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the structured error report generated by the XML Parser Error Recovery prompt. Use this contract to build a post-processing validator before the repaired XML is passed to any downstream system.

Field or ElementType or FormatRequiredValidation Rule

error_report

JSON Object

Top-level key must be present and parse as a valid JSON object.

error_report.original_input_hash

String (SHA-256 hex)

Must match the SHA-256 hash of the raw [MALFORMED_XML] input string, computed by the application harness.

error_report.errors

Array of Objects

Must be a non-empty array if the input is malformed; can be an empty array if no errors are found.

error_report.errors[].line_number

Integer or null

Must be a positive integer if the error is locatable; null only if the error is document-level and not line-specific.

error_report.errors[].error_code

String (enum)

Must be one of: 'UNCLOSED_TAG', 'MISMATCHED_TAG', 'INVALID_ATTRIBUTE', 'UNESCAPED_ENTITY', 'CDATA_TERMINATOR', 'ENCODING_ERROR', 'MULTIPLE_ROOTS', 'OTHER'.

error_report.errors[].message

String

Must be a non-empty string describing the specific error in the context of the malformed input.

error_report.errors[].recovery_suggestion

String

Must be a non-empty string proposing a concrete fix. Must not be a generic message like 'Fix the XML'.

error_report.repaired_xml

String or null

If no repair is possible, must be null. If present, the string must pass a strict XML 1.0 well-formedness parse check in the application harness.

PRACTICAL GUARDRAILS

Common Failure Modes

XML parser error recovery prompts face predictable failure modes when handling real-world malformed markup. These cards cover the most common breaks and how to guard against them before they reach production.

01

Hallucinated Line Numbers

What to watch: The model reports line and column numbers that don't match the actual input, making error reports useless for downstream tooling. This happens when the model estimates positions rather than counting from the provided input. Guardrail: Prepend line numbers to the input XML before sending it to the model, and require the model to reference those explicit line markers in its error report. Validate that reported line numbers exist in the input range.

02

Over-Aggressive Repair That Changes Semantics

What to watch: The model 'fixes' malformed XML by guessing missing elements, reordering siblings, or changing attribute values, producing technically valid XML that no longer represents the original data. This is especially dangerous in financial, healthcare, or legal XML payloads. Guardrail: Require the model to produce a repair diff alongside the repaired document, showing every change made. Add a human-review gate for any repair that modifies element content or attribute values rather than just structure.

03

Unescaped Content in Repaired Output

What to watch: The model produces a repaired XML document that itself contains unescaped special characters, CDATA boundary issues, or encoding mismatches, creating a recursive parsing problem. Guardrail: Run the model's repaired output through a real XML parser as a post-generation validation step. If the repaired document fails to parse, feed the new error back to the model with a retry prompt that includes the specific parser error message.

04

Truncation of Large Malformed Documents

What to watch: When the input XML exceeds context limits, the model silently drops trailing content, losing data and producing an incomplete error report that misses errors in the truncated portion. Guardrail: Chunk large XML documents at safe boundaries before sending to the model. Require the model to report the byte range or line range it processed. Cross-check that the reported range covers the full input length.

05

Misdiagnosis of Encoding Errors

What to watch: The model misidentifies encoding problems as structural errors, or vice versa. A UTF-8 BOM issue gets reported as a missing root element, or a genuinely broken tag structure gets blamed on character encoding. Guardrail: Separate encoding detection from structural analysis in the prompt. Ask the model to first report the detected encoding and any byte-level anomalies, then separately analyze XML structure. Include encoding-specific test cases in your eval suite.

06

Namespace Confusion in Error Context

What to watch: The model reports errors using local element names without namespace qualification, making it impossible to identify which element is broken in documents with multiple namespaces or prefix collisions. Guardrail: Require the model to report errors using Clark notation (e.g., {http://example.com/ns}elementName) or fully qualified names with the prefix as declared in the input document. Validate that namespace URIs in error reports match the input declarations.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the XML Parser Error Recovery prompt before integrating it into a production pipeline. Each criterion targets a specific failure mode common in malformed XML repair tasks.

CriterionPass StandardFailure SignalTest Method

Error Detection Accuracy

All injected malformations are identified with correct line numbers

Missing or incorrect line number for a known error

Inject 5 known XML errors into a valid document; check if all are reported with exact line numbers

Repair Completeness

Repaired XML is well-formed and parses without errors

Repaired XML fails a standard XML parser validation

Parse the [REPAIRED_XML] output with a strict XML parser; test must return true for well-formedness

Recovery Suggestion Relevance

Each error includes a concrete, actionable recovery suggestion

Suggestion is generic, missing, or would not fix the reported error

Manual review of each suggestion against the error type; check if applying the suggestion resolves the malformation

Original Content Preservation

Repaired document retains all non-markup text content from the [MALFORMED_XML] input

Text content is truncated, reordered, or missing in the repaired output

Extract all text nodes from both input and output; diff must show no semantic content loss

Attribute Integrity

All attributes from the original document are preserved with correct values

Attribute is dropped, value is altered, or quote style breaks parsing

Compare attribute key-value pairs between input and repaired output; count mismatches

Namespace Handling

Original namespace declarations are preserved and not duplicated in the repaired document

Namespace is dropped, re-declared on wrong element, or prefix is reassigned

Validate repaired XML against its original namespace schema; check for unresolved prefixes

Encoding Declaration Stability

XML declaration encoding attribute matches the [TARGET_ENCODING] input

Encoding declaration is missing, mismatched, or introduces invalid characters

Check the first line of the repaired output for a valid XML declaration with the correct encoding value

CDATA and Escaped Content Recovery

CDATA sections and escaped characters are correctly reconstructed without double-escaping

CDATA terminator appears unescaped, or entities like & become &amp;

Inject a CDATA section containing ]]> and an ampersand entity; verify the repaired output handles both correctly

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict JSON output schema, retry logic for malformed JSON responses, and a validation step that re-parses the repaired XML. Include a confidence score per fix and a human review flag for destructive repairs.

code
You are an XML error recovery system. Given malformed XML, return a JSON object matching [OUTPUT_SCHEMA].

Rules:
- Report every parse error with line number, column, error code, and severity.
- For each error, propose a repair action and apply it to produce a repaired XML document.
- If a repair removes or rewrites content, set requires_review: true.
- Set repair_confidence: 0.0-1.0 for each fix.
- The repaired_xml field must re-parse without errors.

XML:
[RAW_XML]

Watch for

  • Silent data loss when the model rewrites ambiguous malformed sections
  • Repaired XML that parses but changes semantics
  • Missing requires_review flags on destructive fixes
  • JSON output that doesn't match the schema, breaking downstream parsers
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.