This prompt is designed for platform and infrastructure engineering teams who need to repair model-generated XML configuration files that fail parser validation. The core job-to-be-done is recovering valid XML from a broken output so that an automated deployment pipeline, configuration management system, or application runtime can consume it without manual editing. The ideal user is an engineer building a CI/CD system, a configuration-as-code controller, or an internal platform service where a language model generates XML configs—such as Maven POMs, Apache server configs, Kubernetes XML manifests, or legacy enterprise application descriptors—and those configs must pass an XSD or DTD validation gate before being applied.
Prompt
XML Malformation Correction Prompt Template for Configuration Files

When to Use This Prompt
Identify the specific production failure mode this prompt addresses and when simpler alternatives or manual fixes are the right call.
Use this prompt when the model output is structurally recognizable as XML but contains common syntactic errors: unclosed tags, mismatched opening and closing tags, missing or malformed attribute quotes, incorrect self-closing tag syntax, or namespace prefix inconsistencies. The prompt assumes you have already attempted to parse the output and received a specific parser error message, which becomes a critical input. Do not use this prompt for content-level errors where the XML is syntactically valid but semantically wrong—for example, a correct XML structure that references the wrong port number or an incorrect dependency version. Those failures require a different repair strategy, likely involving retrieval of the correct values from a source of truth rather than structural repair. Also avoid this prompt when the model output is so corrupted that no XML structure is discernible; in that case, regeneration with stricter output constraints or a different model is more reliable than attempting salvage.
Before reaching for this prompt, confirm that you have exhausted simpler fixes: retrying with a lower temperature, adding explicit XML formatting instructions to the generation prompt, or using a model with stronger XML output discipline. This prompt is a recovery mechanism, not a substitute for proper output engineering. When you do use it, always pair it with an XSD validation gate that rejects the repaired output if it still fails, and log the structural diff between the original broken XML and the repaired version so you can monitor whether the underlying generation prompt needs improvement. For high-risk production systems where invalid configuration could cause an outage, require human approval on any repair that modifies more than a configurable threshold of elements.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if XML Malformation Correction is the right tool for your configuration file repair pipeline.
Good Fit: Parser-Rejected Configs
Use when: An XML parser has already rejected the model-generated output with a specific error (unclosed tag, invalid attribute, namespace mismatch). The prompt works best when it receives the raw broken XML and the exact parser error message together. Guardrail: Always feed the original parser error into [VALIDATION_ERROR]—don't ask the model to guess what's wrong.
Bad Fit: Semantic Logic Errors
Avoid when: The XML parses successfully but contains wrong values, incorrect hierarchy, or configuration logic errors. This prompt repairs syntax and structure, not business logic. Guardrail: Route parse-success-but-logic-failure cases to a schema-aware validation prompt or human review, not this repair template.
Required Input: XSD Schema
Risk: Without an XSD schema, the repair prompt may produce valid XML that violates element ordering, required attributes, or allowed value constraints. Guardrail: Always provide [XSD_SCHEMA] as input. Run the repaired output through an XSD validation gate before accepting it. If no XSD exists, use a structural-only repair variant.
Operational Risk: Silent Corruption
Risk: The model may silently drop an attribute or close a tag in the wrong location, producing valid XML that misconfigures a system. Guardrail: Always generate and review the structural diff output. Compare the repaired XML against the original broken input and flag any unexpected structural changes for human approval before applying.
Bad Fit: Multi-Megabyte Configs
Avoid when: The broken XML file exceeds the model's context window or token budget. Large configuration files with thousands of elements will cause truncation or incomplete repair. Guardrail: Chunk large configs by logical section (e.g., one service block at a time) and repair incrementally. Validate each chunk independently before reassembly.
Good Fit: CI/CD Pipeline Integration
Use when: You have an automated pipeline that generates XML configs via an LLM and needs a repair step before deployment. The prompt fits as a post-generation recovery layer. Guardrail: Implement a retry loop: parse → fail → repair → re-parse → XSD validate. Escalate to human review after [MAX_RETRIES] attempts. Never auto-apply repaired configs without validation passing.
Copy-Ready Prompt Template
A reusable prompt with placeholders for repairing malformed XML configuration files against a target XSD schema.
This prompt template is designed to be copied directly into your application's prompt layer. It instructs the model to act as a strict XML repair engine, taking a malformed XML string and a set of constraints, and returning a structurally valid, well-formed XML document. The square-bracket placeholders are the dynamic inputs your application must supply at runtime. Do not modify the core instruction logic; instead, populate the placeholders with the specific data for each repair job.
textYou are an XML repair engine. Your only task is to fix malformed XML configuration files. You will receive a malformed XML string and must return a structurally valid, well-formed XML document. Follow these rules strictly: 1. Analyze the [MALFORMED_XML] for common errors: unclosed tags, mismatched closing tags, missing or unquoted attributes, incorrect self-closing tag syntax, and namespace prefix issues. 2. Repair all syntax errors to produce well-formed XML. Do not change the semantic content or element values unless they are syntactically invalid. 3. If a tag is unclosed, determine the correct closing point based on sibling elements and document structure. Do not guess content. 4. Ensure all attribute values are enclosed in double quotes. 5. If [TARGET_XSD] is provided, validate the repaired XML against this XSD schema. If the repaired XML violates the schema, make the minimal structural changes required to achieve schema validity, such as adding missing required elements or reordering elements. Flag any semantic changes in a processing instruction comment: <!-- REPAIR NOTE: [description of change] -->. 6. If the input is too damaged to repair with high confidence, output only the following XML comment and nothing else: <!-- REPAIR FAILED: [brief reason] -->. 7. Output ONLY the repaired XML document. Do not include any other text, explanation, or markdown fences. [MALFORMED_XML]: [INPUT_XML] [TARGET_XSD]: [OPTIONAL_XSD_SCHEMA]
To adapt this template, replace [INPUT_XML] with the broken XML string and [OPTIONAL_XSD_SCHEMA] with your XSD schema string. If no schema is available, pass an empty string or remove the entire [TARGET_XSD] block and the associated rule #5. The [MALFORMED_XML] and [TARGET_XSD] labels are part of the prompt structure and should not be removed. For high-risk configuration systems, always provide the [TARGET_XSD] to add a critical structural validation layer. The next step after generating a repair is to run the output through a native XML parser and, if a schema was provided, a validating XML reader in your application code. Never trust a model-repaired config without this programmatic validation gate.
Prompt Variables
Required inputs for the XML Malformation Correction Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is usable before incurring model cost.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[MALFORMED_XML] | The broken XML string that failed parser validation. This is the primary input to repair. | <config><server host='prod01" port=8080></server></config> | Must be a non-empty string. If empty or null, abort before model call. Check that the string contains angle brackets; if not, the input may be a parser error message rather than XML content. |
[ERROR_MESSAGE] | The exact parser error message returned when [MALFORMED_XML] was last parsed. Provides the model with the specific failure location and type. | XMLSyntaxError: Unquoted attribute value at line 3, column 24 | Must be a non-empty string. Prefer raw parser output over human summaries. If the error message is generic or truncated, re-parse [MALFORMED_XML] with a strict parser to capture the full error before calling the model. |
[XSD_SCHEMA] | Optional XSD schema string used to validate the repaired output. When provided, the model must ensure the repaired XML conforms to this schema. | <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">...</xs:schema> | If provided, must be valid XSD. Validate [XSD_SCHEMA] with an XSD parser before passing to the model. If the schema itself is malformed, repair is unreliable. Set to null if no schema validation is required. |
[NAMESPACE_MAP] | Optional mapping of namespace prefixes to URIs used in the target XML. Helps the model resolve namespace-related errors. | {"cfg": "http://example.com/config", "xsi": "http://www.w3.org/2001/XMLSchema-instance"} | If provided, must be a valid JSON object with string keys and string values. Each URI should be a well-formed absolute URI. If [MALFORMED_XML] uses namespaces but [NAMESPACE_MAP] is null, the model may hallucinate namespace declarations. |
[OUTPUT_SCHEMA] | The expected structure of the model's JSON response containing the repair result, diff, and validation status. | {"repaired_xml": "string", "changes": [{"line": "int", "issue": "string", "fix": "string"}], "xsd_valid": "boolean", "parser_valid": "boolean"} | Must be a valid JSON Schema or a clear structural description. The model output must be parseable as JSON matching this contract. If [OUTPUT_SCHEMA] is missing, the model may return free text instead of structured repair data. |
[CONSTRAINTS] | Hard rules the model must follow during repair, such as preserving comments, not reordering elements, or flagging ambiguous fixes for human review. | Do not reorder elements. Preserve all XML comments. Flag any fix with confidence below 0.9 for human review. | Must be a non-empty string or array of constraint strings. Each constraint should be testable. Avoid vague constraints like 'be careful.' If [CONSTRAINTS] is empty, the model may apply destructive fixes like removing problematic sections entirely. |
Implementation Harness Notes
How to wire the XML malformation correction prompt into a production repair pipeline with validation gates, retry logic, and audit trails.
This prompt is designed to sit inside a post-generation repair loop, not as a standalone chat interaction. The typical integration pattern is: (1) model generates XML configuration, (2) parser validation fails with specific error messages, (3) the failed XML and parser errors are fed into this prompt, (4) the corrected XML is re-validated, and (5) the loop either succeeds, retries, or escalates. The prompt expects two required inputs: [MALFORMED_XML] (the raw string that failed parsing) and [PARSER_ERRORS] (the exact error output from your XML parser or XSD validator). Optionally, provide [XSD_SCHEMA] if structural validation against a schema is required, and [CORRECTION_CONSTRAINTS] to enforce domain-specific rules like forbidden elements or required namespaces.
Validation gate and retry loop: After receiving the corrected XML, immediately run it through the same parser that produced the original errors. If the parser returns zero errors, the repair succeeded and the output can proceed downstream. If errors remain, compare the new error count to the original—if it decreased, retry with the updated XML and new errors (up to a configurable MAX_RETRIES, typically 3). If errors are unchanged or increased, break the loop and escalate for human review. Structural diff requirement: The prompt instructs the model to output a corrections_applied array describing each fix. Parse this array and compare it against the actual byte-level diff between input and output XML. If the model claims to have fixed an unclosed tag but the diff shows no change to that element, flag the output for review—this is a hallucination pattern we've observed in production. Model choice: This task benefits from models with strong code and structured text capabilities. GPT-4o and Claude 3.5 Sonnet perform well on XML repair. Avoid smaller or older models (GPT-3.5, Claude Haiku) for deeply nested or namespace-heavy XML—they tend to introduce new errors while fixing old ones. For air-gapped or private deployments, Llama 3.1 70B with careful temperature settings (0.1-0.2) is viable but requires more aggressive retry logic.
Logging and audit trail: Every repair attempt should be logged with: input XML hash, parser error count before repair, correction prompt version, model used, output XML hash, parser error count after repair, retry count, and whether human review was triggered. This audit trail is critical for configuration files that affect infrastructure, deployments, or security policies. When to avoid this prompt: Do not use this prompt for XML documents where semantic correctness matters more than syntactic validity—for example, legal contracts or medical records where a well-formed but semantically altered document is worse than a malformed one. In those cases, flag the malformed output for human correction immediately. Also avoid this prompt when the malformed XML is truncated due to token limits; use the Token Limit Truncation Recovery Prompt instead, as this prompt may hallucinate missing content rather than detecting truncation.
Expected Output Contract
Defines the exact structure, types, and validation rules for the corrected XML output. Use this contract to programmatically validate the model's response before accepting the repair.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
corrected_xml | String (valid XML) | Must parse successfully with a standard XML parser. No unclosed tags, mismatched attributes, or illegal characters. | |
repair_log | Array of objects | Each entry must contain 'line' (integer), 'issue' (string from allowed enum), and 'action' (string). Array must not be empty if changes were made. | |
repair_log[].line | Integer | Must be a positive integer corresponding to the approximate line number in [MALFORMED_XML] where the issue was detected. | |
repair_log[].issue | Enum string | Must be one of: 'UNCLOSED_TAG', 'ATTRIBUTE_QUOTING', 'SELF_CLOSING_ERROR', 'NAMESPACE_ERROR', 'ILLEGAL_CHARACTER', 'COMMENT_ERROR', 'CDATA_ERROR'. | |
repair_log[].action | String | Must be a non-empty string describing the specific correction applied, e.g., 'Added closing tag </config>'. | |
xsd_valid | Boolean | Must be true if [XSD_SCHEMA] is provided. If false, the output is considered a failure. If no XSD is provided, this field should be null. | |
structural_diff | String (Unified Diff) | If provided, must be a valid unified diff format showing changes between [MALFORMED_XML] and corrected_xml. Null if no changes were needed. | |
unrecoverable_errors | Array of strings | If present, each string must describe a specific error that could not be automatically repaired. If the array is not empty, corrected_xml may still be partially valid. |
Common Failure Modes
XML repair prompts fail in predictable ways. These are the most common production failure modes and the guardrails that catch them before they corrupt downstream configuration systems.
Silent Structural Drift
What to watch: The model repairs well-formedness errors but silently changes element hierarchy, reorders siblings, or collapses nested structures that were semantically significant. The output passes XML parsing but breaks application logic. Guardrail: Always run a structural diff (xmldiff or equivalent) between the original malformed input and the repaired output. Flag any unexpected tree mutations for human review before applying the config.
Content Truncation on Unclosed Tags
What to watch: When the model encounters deeply nested unclosed tags near token limits, it may close the document prematurely by inserting synthetic closing tags, discarding legitimate content that followed the malformed region. Guardrail: Compare the character count and element count of the repaired output against the original. If the repaired document is significantly smaller, trigger a continuation request or flag for manual reconstruction of the truncated section.
Attribute Value Hallucination
What to watch: When attribute values are missing or malformed, the model may invent plausible values (default ports, common paths, placeholder URLs) instead of leaving them empty or flagging them as unrecoverable. Guardrail: Require the prompt to output an unrecovered_fields array alongside the repaired XML. Post-process by validating all attribute values against expected patterns or enumerations from the XSD. Reject invented values that don't match known configuration ranges.
Namespace Declaration Loss
What to watch: The model repairs tag structure but drops or incorrectly remaps namespace declarations (xmlns), causing the repaired XML to fail XSD validation even though it's well-formed. Common with default namespace handling. Guardrail: Extract all namespace declarations from the original malformed input before repair. After repair, verify every original namespace URI is still declared and that prefixed elements still resolve correctly. Run XSD validation with the exact target namespace set.
Encoding and Entity Corruption
What to watch: The model mishandles XML character entities (&, <, 
) or non-UTF-8 byte sequences during repair, converting them to literal characters or dropping them entirely. This breaks configs that rely on entity-escaped values. Guardrail: Before repair, catalog all entity references and CDATA sections in the original. After repair, verify each entity is either preserved or correctly re-escaped. Reject outputs where entity counts don't match unless the diff explicitly shows intentional conversion.
Self-Closing Tag Ambiguity
What to watch: The model converts empty elements between <tag></tag> and <tag/> forms inconsistently, which can break XSD validation when the schema requires a specific form for element content models. Guardrail: Include the XSD or DTD in the prompt context and instruct the model to preserve the original empty-element style unless the schema explicitly requires a specific form. Post-validate with xmllint --schema to catch content model violations caused by self-closing tag choices.
Evaluation Rubric
Criteria for testing the XML Malformation Correction Prompt before deployment. Each row defines a pass standard, a failure signal, and a concrete test method to validate output quality.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Parser Validation | Output passes XML 1.0 well-formedness check with zero errors | Parser throws fatal error or returns non-zero error count | Run output through |
XSD Schema Compliance | Output validates against [TARGET_XSD] with zero schema violations | XSD validator reports element not allowed, missing required attribute, or type mismatch | Validate output against [TARGET_XSD] using |
Structural Fidelity | Element hierarchy, nesting depth, and sibling order match [ORIGINAL_XML] structure exactly | Elements reordered, missing, duplicated, or nested at wrong depth compared to original | Generate structural diff between [ORIGINAL_XML] and repaired output; assert diff contains only repaired nodes, not structural changes |
Content Preservation | All text content, attribute values, and CDATA sections from [ORIGINAL_XML] are present and unchanged | Text content truncated, attribute values altered, or CDATA sections lost | Extract all text nodes and attribute values from both documents; assert set equality with tolerance for whitespace normalization |
Self-Closing Tag Correctness | Self-closing tags use correct | Self-closing tags written as open-close pairs | Compare self-closing tag style per element against [ORIGINAL_XML]; assert style preservation for elements where convention matters |
Namespace Integrity | All namespace declarations from [ORIGINAL_XML] are preserved; no namespace URIs altered or dropped | Missing | Extract all namespace declarations using XPath |
Attribute Quoting Repair | All attribute values are double-quoted; unquoted or single-quoted attributes from malformed input are corrected | Any attribute value remains unquoted or single-quoted after repair | Regex scan output for |
No Hallucinated Content | Output contains no elements, attributes, or text nodes not present in [ORIGINAL_XML] | New elements, guessed closing tags, or invented attribute values appear in output | Compute node set difference between [ORIGINAL_XML] and output; assert all output nodes have a corresponding node in original |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single XSD file and lighter validation. Remove the structural diff output requirement and focus on repair-only. Accept best-effort fixes without strict namespace resolution.
codeRepair the following XML configuration so it passes basic XML well-formedness checks. Fix unclosed tags, unquoted attributes, and self-closing tag errors. [INPUT_XML]
Watch for
- Missing XSD validation means semantic errors slip through
- Overly broad instructions may rewrite valid sections
- No diff output makes it hard to audit what changed

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us