Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Structure XML Tags in Claude 3.5 Sonnet for Bulletproof Structured Output Without Heavy SDKs

SDKs like Instructor and Pydantic are great, but they add unnecessary weight. Learn how to leverage Claude's native XML-parsing strengths to get reliable, structured data out of your prompts with zero external dependencies.

Updated 11/2/2026

When building AI-powered web applications, you almost always need structured outputs like JSON to update databases, render UI cards, or trigger internal APIs.

To solve this, developers often reach for heavy, schema-forcing Python or TypeScript SDKs. While libraries like Instructor or LangChain are useful, they introduce unnecessary complexity, abstract away your raw prompts, and occasionally break when the underlying model updates its API.

There is a simpler, more robust way. By leveraging native XML parsing in /platforms/claude, you can reliably extract clean, structured data with no extra SDKs, no external dependencies, and absolute control over your outputs.

Why Claude Loves XML

Anthropic's models are trained from the ground up on text structured with XML tags (like <instructions>, <example>, and <output>). While models like GPT-4 are highly optimised for parsing JSON objects, Claude uses XML as its native markup language.

If you ask Claude to output raw JSON, it often prefixes the code block with polite preamble ("Here is the JSON you requested:") or appends conversational filler at the end. This extra text breaks standard parser scripts. However, if you instruct Claude to output its response wrapped inside custom XML tags, it will consistently produce clean, structured data that is incredibly easy to extract using basic string manipulation or native standard libraries.

To build better templates, you can check out our custom prompt helper at /prompts to experiment with custom markup structures.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

The "Double-Walled" XML Prompt Strategy

To get flawless structured outputs from Claude 3.5 Sonnet, we use a technique called Double-Walled XML Prompting. We do this in three stages:

  1. Define the desired output schema inside XML tags in our system prompt.
  2. Ask Claude to perform its analytical thinking inside a set of <thought> tags first. This keeps the model's intermediate steps separate from the raw data we want to parse.
  3. Instruct Claude to output the final data wrapped inside clear, custom data tags, such as <json_data>.

Let us write a clean, dependency-free Python function to demonstrate this in action.

Step-by-Step Implementation in Python

Create a new file named xml_parser.py. We will use nothing but the official Anthropic SDK and Python's built-in xml.etree.ElementTree parser to handle the response.

First, install the Anthropic library:

`bash pip install anthropic `

Now, add the following code to implement the parser and run a test query:

`python import os import json import xml.etree.ElementTree as ET from anthropic import Anthropic

Initialize client client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

def extract_user_profiles(raw_text: str) -> dict: """ Uses Claude 3.5 Sonnet to parse unstructured text into structured JSON, relying entirely on XML tagging for layout constraint. """ system_prompt = ( "You are a highly precise data extraction pipeline. Your task is to process " "unstructured text and extract user profile information. " "You MUST structure your response using specific XML tags as follows:\n\n" "1. Wrap your internal reasoning and analysis inside <thinking> tags.\n" "2. Wrap the final structured JSON object inside <data_payload> tags.\n\n" "The JSON inside <data_payload> must adhere strictly to this schema:\n" "{\n" " \"profiles\": [\n" " {\n" " \"name\": \"string\",\n" " \"role\": \"string\",\n" " \"skills\": [\"string\"]\n" " }\n" " ]\n" "}\n\n" "Do not include any other text, pleasantries, or explanations outside these tags." ) prompt = f"Extract profiles from this source text:\n\n{raw_text}" response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1500, temperature=0.1, # Low temperature prioritises precise data extraction system=system_prompt, messages=[{"role": "user", "content": prompt}] ) return parse_xml_response(response.content[0].text)

def parse_xml_response(response_text: str) -> dict: """ Parses the response text to extract only the JSON payload within <data_payload> tags. """ try: # We wrap the response in a dummy root tag to ensure valid XML parsing wrapped_xml = f"<root>{response_text}</root>" root = ET.fromstring(wrapped_xml) # Extract the contents of the thinking tag to display or log if needed thinking_tag = root.find("thinking") if thinking_tag is not None: print("--- Claude's Internal Chain of Thought ---") print(thinking_tag.text.strip()) print("-----------------------------------------\n") # Extract and load the JSON payload data_payload = root.find("data_payload") if data_payload is not None: json_string = data_payload.text.strip() return json.loads(json_string) else: raise ValueError("Could not find <data_payload> tags in response.") except ET.ParseError as e: print(f"XML Parsing failed: {e}") print(f"Raw response was: {response_text}") # If you run into parsing bugs, troubleshooting tips are available at /platforms/claude/articles raise

if __name__ == "__main__": unstructured_source_data = ( "Our development team is expanding. Sarah Jenkins is our Lead Platform Engineer. " "She handles Python and Kubernetes. We also have David Chen, who is on the frontend " "team building React apps with TypeScript. He is also quite skilled in Figma." ) print("Sending request to Claude...") parsed_output = extract_user_profiles(unstructured_source_data) print("--- Final Parsed JSON Output ---") print(json.dumps(parsed_output, indent=2)) `

Why This Method is Better Than SDKs

By avoiding complex third-party wrappers, you enjoy three main benefits:

  • Zero Latency on Schema Updates: When Anthropic updates its models, you don't have to wait for an open-source SDK maintainer to release a patch. Your parsing relies on core Python libraries that do not change.
  • Separation of Reasoning: Giving Claude space to think inside <thinking> tags before writing any code drastically reduces syntax mistakes. The model can figure out how to structure complex nests before outputting the final JSON.
  • Clearer Debugging: If Claude gets confused by input text, you can read the contents of the <thinking> tag to understand exactly where the logical breakdown occurred.
claudepythonprompt-engineeringtutorialsdev-workflow

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.