Inferensys

Prompt

Missing Closing Tag Repair Prompt for XML

A practical prompt playbook for using Missing Closing Tag Repair Prompt for XML in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the exact job this prompt performs, the operator who should run it, and the production boundaries where it stops being the right tool.

This prompt is designed for backend platform engineers and integration developers who operate XML processing pipelines where a large language model generates structured XML documents that are occasionally truncated by token limits, streaming interruptions, or model early-stopping. The primary job-to-be-done is to recover a well-formed, schema-valid XML document from a partial, malformed input that is missing one or more closing tags. The prompt instructs the model to infer the correct closing tags, repair any broken attribute quoting, and restore proper tag nesting without altering the existing content or inventing new element bodies. This is a post-generation repair step, not a content generation or schema design task.

Use this prompt when you have a partial XML string that fails a standard XML parser with errors such as 'unexpected end of file', 'missing closing tag', or 'unclosed token'. The input must contain enough structural context for the model to determine the intended hierarchy—typically a truncated document where the opening tags and most of the content are intact, but the final closing tags are absent. The prompt is most effective when paired with a known XML Schema Definition (XSD) or a set of expected parent-child relationships that can be provided as [CONSTRAINTS]. Do not use this prompt for XML documents that are entirely garbled, have no discernible tag structure, or require content generation to fill missing element values. It is also inappropriate for documents where the truncation point occurs inside a critical data field whose value cannot be inferred without external knowledge.

Before routing to this prompt, your application harness should first attempt standard XML repair heuristics: closing unclosed tags in reverse order of opening, fixing obvious quote mismatches, and stripping trailing incomplete content. If those deterministic methods fail, this prompt becomes the recovery path. The prompt expects you to supply the partial XML as [INPUT], an optional [XML_SCHEMA] or tag-nesting rules as [CONSTRAINTS], and a clear [OUTPUT_SCHEMA] specifying that only well-formed XML should be returned with no explanatory text. For high-stakes pipelines—such as configuration generation, financial reporting, or clinical document processing—always route the repaired output through XML schema validation and a human review step before the document reaches downstream systems. The next section provides the exact prompt template you can copy and adapt.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Missing Closing Tag Repair Prompt works, where it fails, and what you must provide before using it in production.

01

Good Fit: Truncated XML Documents

Use when: an XML document was cut off by token limits, streaming interruptions, or model early-stopping, and the partial content is otherwise valid. Guardrail: always validate the repaired output against the expected XSD or DTD before ingestion.

02

Bad Fit: Semantically Corrupted XML

Avoid when: the XML content itself is garbled, hallucinated, or contains invented elements not present in the source. Tag repair cannot fix semantic errors. Guardrail: run a schema mismatch detection prompt first if content fidelity is suspect.

03

Required Input: Partial XML Fragment

What you must provide: the truncated XML string, the known or inferred root element name, and optionally the expected schema. Without the root element context, the model may guess incorrectly. Guardrail: include the last complete sibling element as context for nesting inference.

04

Operational Risk: Incorrect Nesting

What to watch: the model may close tags in the wrong order, producing well-formed but semantically incorrect XML. Guardrail: add an XPath-based structural assertion to your eval harness that checks parent-child relationships against the schema.

05

Operational Risk: Attribute Truncation

What to watch: if truncation occurs mid-attribute value, the model may fabricate a plausible value or leave the attribute unclosed. Guardrail: flag any repaired attribute with a confidence marker and require human review for attributes sourced from regulated data.

06

Not a Replacement for Token Management

Avoid when: you can prevent truncation by increasing max_tokens, using streaming with reassembly, or splitting generation into smaller chunks. Repair is a recovery path, not a design pattern. Guardrail: monitor truncation rate and alert if repair frequency exceeds 5% of requests.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for repairing truncated XML documents by inferring and inserting missing closing tags.

This prompt template is designed to be copied directly into your application code or prompt management system. It instructs the model to act as an XML repair engine, taking a truncated XML string and returning only the repaired, well-formed document. The template uses square-bracket placeholders for all dynamic inputs, ensuring you can wire it into a production harness without manual string surgery.

text
You are an XML repair engine. Your only job is to repair truncated XML documents.

You will receive an XML document that was cut off mid-generation. The document may be missing closing tags, have unclosed attribute values, or contain incomplete nested structures.

Your task:
1. Analyze the provided XML fragment to understand its structure, namespace declarations, and tag hierarchy.
2. Infer and insert all missing closing tags to make the document well-formed.
3. Repair any unclosed attribute values by adding the missing quotation mark.
4. Preserve all existing content, attributes, and structure exactly as provided. Do not change, add, or remove any content except the minimum required to close open elements.
5. Do not add any commentary, explanation, or markdown formatting. Output only the repaired XML document.

Input XML:
[TRUNCATED_XML]

Repaired XML:

To adapt this template, replace [TRUNCATED_XML] with the partial XML string from your application. For stricter control, you can add an [XML_SCHEMA] placeholder to provide an XSD or DTD for validation-aware repair. If the document uses a known root element, prepend a constraint like The root element must be <[ROOT_ELEMENT]>. Always test the repaired output with a strict XML parser before returning it to any downstream system. For high-risk pipelines, route outputs that fail parser validation to a human review queue rather than silently accepting malformed XML.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Missing Closing Tag Repair Prompt. Each variable must be supplied at runtime for reliable XML repair. Validate inputs before calling the model to prevent cascading repair failures.

PlaceholderPurposeExampleValidation Notes

[TRUNCATED_XML]

The incomplete XML document with missing closing tags, broken attribute quoting, or severed element boundaries

<root><item id="1"><name>Widget</name><price>19.99</price></item><item id="2"><name>Gadget

Must be a non-empty string. Validate that input contains at least one unclosed XML tag. Reject if already well-formed or if input is empty.

[XML_SCHEMA]

Optional XSD or DTD reference defining expected element structure, required attributes, and nesting rules

XSD: element 'root' requires child 'item' with attributes 'id' (required, integer) and child elements 'name', 'price'

If null, repair uses structural inference only. If provided, validate schema is parseable before passing to prompt. Schema mismatch with partial input triggers schema-aware repair mode.

[KNOWN_ELEMENTS]

List of valid element names expected in the document to constrain tag inference and prevent hallucinated elements

["root", "item", "name", "price", "description", "category"]

Must be a JSON array of strings or null. When provided, repair must not introduce elements outside this set. Validate list is non-empty if supplied.

[MAX_DEPTH]

Maximum nesting depth allowed for inferred closing tags to prevent runaway recursion in deeply nested documents

5

Must be a positive integer between 1 and 20. Defaults to 10 if null. Used to bound repair complexity and prevent infinite tag insertion loops.

[PRESERVE_CONTENT]

Boolean flag indicating whether partial text content inside truncated elements should be preserved or discarded

Must be true or false. When true, repair retains all partial text nodes and attribute values. When false, truncated content may be dropped if unrecoverable. Validate boolean type before prompt assembly.

[OUTPUT_FORMAT]

Specifies whether the repaired output should be minified, pretty-printed with indentation, or returned as-is matching input style

"pretty-print"

Must be one of: "minified", "pretty-print", "preserve-style". Defaults to "preserve-style" if null. Affects post-repair formatting pass, not structural repair logic.

[FAILURE_MODE]

Controls behavior when repair confidence is low or unrecoverable structural damage is detected

"flag-and-return"

Must be one of: "flag-and-return", "best-effort", "reject". "flag-and-return" inserts XML comments marking uncertain repairs. "best-effort" repairs silently. "reject" returns error if any uncertainty exists. Validate enum membership.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Missing Closing Tag Repair Prompt into a production XML repair pipeline with validation, retries, and safe failure modes.

This prompt is designed to be called as a post-generation repair step, not as the primary generation prompt. Wire it into your application immediately after an XML validation failure. The typical flow is: (1) receive raw model output, (2) attempt XML parsing, (3) on parse failure, extract the partial XML string and the parser error message, (4) call this repair prompt with both the partial XML and the error context, (5) attempt to parse the repaired output, and (6) either proceed with the valid XML or escalate to a human or dead-letter queue after a defined retry budget is exhausted.

Input assembly: The prompt expects two variables: [PARTIAL_XML] (the truncated or malformed XML string) and [ERROR_CONTEXT] (the parser error message, line number, and column if available). Do not pass the entire conversation history or unrelated context—this prompt works best with a narrow, focused input. If your XML has a known schema, include a [SCHEMA_HINT] variable with the expected root element and required child elements to guide the repair. Model choice: Use a model with strong code and structure reasoning (GPT-4o, Claude 3.5 Sonnet, or equivalent). Smaller or older models often introduce new structural errors during repair. Set temperature=0 to maximize deterministic, well-formed output. Validation gate: After receiving the repaired XML, run it through your standard XML parser. If parsing fails again, increment a retry counter. On the second retry, include the new error message in [ERROR_CONTEXT] to give the model more specific guidance. Do not retry more than twice without human review—beyond two attempts, the model is likely to hallucinate content rather than repair structure.

Logging and observability: Log every repair attempt with: the original partial XML length, the parser error, the repaired XML length, parse success/failure, and the retry count. This data is critical for detecting systemic issues—if repair rates drop below 90%, your primary generation prompt likely needs adjustment, not more repair attempts. Tool integration: If your application uses function calling, expose this prompt as a tool with a schema like repair_xml(partial_xml: string, error_context: string, schema_hint?: string) -> repaired_xml: string. This allows an agent or orchestrator to call repair automatically when an XML validation tool returns an error. When to avoid this prompt: Do not use this prompt for XML documents that are missing more than 30% of their expected content—at that point, regeneration with the original task context is more reliable than repair. Do not use it for security-critical XML (e.g., SAML assertions, signed documents) where structural repair could alter security semantics. In regulated environments, flag all repaired XML for human review before it enters downstream systems of record.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the repaired XML document returned by the prompt. Use this contract to build automated post-processing checks before the output reaches any downstream XML parser or application.

Field or ElementType or FormatRequiredValidation Rule

repaired_xml

String (XML 1.0)

Must parse successfully with a strict XML parser. No unclosed tags, unescaped entities, or attribute quote mismatches allowed.

repaired_xml.root_element

String

Must match the root element name from [ORIGINAL_TRUNCATED_XML]. Schema check: root tag name must be identical to the input's root.

repair_log

Array of Objects

Each object must contain 'line' (Integer), 'issue' (String from enum: MISSING_CLOSING_TAG, UNCLOSED_ATTRIBUTE, UNESCAPED_ENTITY, MALFORMED_COMMENT), and 'action' (String). Array must not be empty.

repair_log[].line

Integer

Must be a positive integer corresponding to the approximate line number in the original truncated input where the issue was detected.

repair_log[].issue

String (Enum)

Must be one of: MISSING_CLOSING_TAG, UNCLOSED_ATTRIBUTE, UNESCAPED_ENTITY, MALFORMED_COMMENT. No other values allowed.

repair_log[].action

String

Must describe the specific repair performed, including the tag or entity involved. Example: 'Inserted closing tag </record> for element at line 42'.

confidence_score

Float (0.0-1.0)

Must be a float between 0.0 and 1.0. Represents the model's confidence that all structural issues were identified and correctly repaired. A score below 0.8 should trigger a human review or retry.

unrecoverable_fragments

Array of Strings

If present, each string must contain a snippet of the original input that could not be repaired with high confidence. If the repair was fully successful, this field must be an empty array or omitted.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when repairing truncated XML and how to guard against it in production.

01

Nesting Mismatch After Repair

What to watch: The model closes tags in the wrong order, producing <parent><child></parent></child> instead of correct nesting. This happens when truncation severs deeply nested structures and the model guesses the close sequence. Guardrail: Run a strict XML well-formedness parser after every repair. If nesting fails, re-prompt with the parser error message and the original partial XML. Track nesting-depth deltas in eval harness.

02

Hallucinated Content in Inferred Tags

What to watch: The model invents element content, attribute values, or entire sibling elements that were not present in the original partial XML. This is especially dangerous when repairing data payloads where fabricated values corrupt downstream systems. Guardrail: Diff the repaired output against the original partial input. Flag any character content or attribute values that were not present in the truncated source. Require human review when new content exceeds a configurable threshold.

03

Attribute Quote Boundary Corruption

What to watch: Truncation severs an attribute value mid-quote, leaving attr="partial or attr='partial. The model may incorrectly close the quote, drop the attribute, or mangle the value. Guardrail: Pre-process the truncated XML to detect unclosed attribute quotes before sending to the repair prompt. If detected, strip the broken attribute and flag it for the model to infer from context rather than guess from corrupted syntax.

04

Namespace and Prefix Dropping

What to watch: The model closes tags using bare element names instead of their namespace-qualified prefixes, producing <ns:tag></tag> mismatches. Common in SOAP, XSLT, or schema-validated XML where prefix consistency is mandatory. Guardrail: Extract namespace declarations from the partial input and include them explicitly in the repair prompt as a [NAMESPACE_MAP] variable. Validate prefix consistency in the eval harness using the declared namespace bindings.

05

Self-Closing Tag Ambiguity

What to watch: The model converts a truncated container element into a self-closing tag (<element/>) instead of inferring it should have child content. This silently drops expected structure. Guardrail: Compare the schema or DTD for the target element. If the element definition requires child content, reject self-closing repairs. Include schema cardinality hints in the prompt as [ELEMENT_CONSTRAINTS] to guide the model toward correct closure style.

06

Encoding Declaration Corruption

What to watch: Truncation severs the XML declaration (<?xml version="1.0" encoding="UTF-8"?>) or the model prepends a duplicate declaration to the repaired output. This breaks XML parsers that expect exactly one declaration at position zero. Guardrail: Strip any existing declaration from the partial input before repair. Re-add a single correct declaration as a post-processing step. Validate that the final output contains exactly one XML declaration at byte offset zero.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality of repaired XML output before shipping. Use these checks in your eval harness to gate deployment.

CriterionPass StandardFailure SignalTest Method

XML Well-Formedness

Output parses without errors by a strict XML parser (e.g., lxml, Xerces).

Parser throws fatal error: mismatched tag, unclosed attribute, or invalid character.

Parse output with strict XML parser; assert no parse errors.

Tag Nesting Correctness

All opening tags have corresponding closing tags in correct nesting order.

Parser reports tag mismatch; manual inspection reveals interleaved or missing close tags.

Validate against XML Schema (XSD) or DTD; assert nesting depth consistency.

Attribute Quoting Repair

All attribute values are enclosed in matching single or double quotes.

Parser reports unquoted attribute value; attribute value contains unescaped quote character.

Regex check for unquoted attributes; parse output and iterate all element attributes for quote integrity.

Input Content Preservation

All text content and attributes from the truncated input appear unmodified in the repaired output.

Original text is altered, reordered, or missing; new hallucinated content appears.

Diff original truncated input against repaired output; assert no deletions or modifications to existing content.

No Hallucinated Additions

Repaired output contains only the closing tags and quote fixes necessary; no new elements, attributes, or text are invented.

Extra elements, attributes, or text nodes appear that were not implied by the truncated input.

Compare element and attribute counts before and after repair; assert only structural closures added.

Schema Compliance

Repaired output validates against the expected XML Schema Definition (XSD) if provided.

Schema validator reports missing required elements, wrong element order, or invalid attribute values.

Validate repaired output against [TARGET_SCHEMA]; assert no schema violations.

Encoding Consistency

Output encoding matches the declared encoding in the XML declaration or defaults to UTF-8.

Encoding declaration mismatch; non-UTF-8 characters corrupted; byte-order mark issues.

Check XML declaration encoding attribute; validate byte sequence matches declared encoding.

Truncation Boundary Handling

Repair correctly handles the exact point of truncation without duplicating or dropping characters at the boundary.

Duplicated partial tag name at boundary; missing angle bracket; text content split mid-character.

Inject known truncation points; assert boundary characters appear exactly once in correct order.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single XML sample and minimal validation. Drop the schema validation step and rely on visual inspection of well-formedness.

code
[SYSTEM]: You are an XML repair tool. Given a truncated XML document, infer and insert missing closing tags to produce well-formed XML. Preserve all existing content and attributes.

[INPUT]: [TRUNCATED_XML]

Watch for

  • Missing tag-nesting checks—the model may close tags in the wrong order
  • No attribute quoting repair when quotes were severed mid-attribute
  • Overly aggressive completion that invents sibling elements beyond the truncation point
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.