Extract and Safely Parse an XML Document Nested in CDATA
StringsModel answerLast updated
Implement a function that pulls a nested XML document out of a CDATA section and reads an attribute from its root, while blocking XXE and entity-expansion attacks.
Background
You're writing a middleware component that ingests messages from legacy systems. Each message is a well-formed XML envelope, but one specific field carries a second, self-contained XML document stored verbatim inside a CDATA section. Your job is to safely unpack that inner document and read a named attribute from its root element.
Task
Implement the function below:
def extract_and_parse_nested(xml_string: str, target_tag: str, attribute_name: str) -> str:
"""
1. Parse xml_string as an XML document.
2. Find the first element whose tag matches target_tag.
3. Treat that element's text content as a second XML document.
4. Return the value of attribute_name on the root of that second document.
Return "" if anything is absent, malformed, or unsafe.
"""
pass
Example
Given this envelope:
<message>
<data><![CDATA[<record id="A123"><body>Content</body></record>]]></data>
</message>
Called as extract_and_parse_nested(xml_string, "data", "id"), the function should return "A123".
Constraints and requirements
- Return
""for every failure condition instead of raising. The middleware must not crash the processing pipeline. - The input may be malformed at the outer or inner level.
target_tagmay be absent in the outer document, or the element may be empty.- The inner content may not be valid XML.
- Security: both the outer envelope and the inner payload must be parsed with protections against XML External Entity (XXE) injection and entity-expansion (billion-laughs) attacks.
- Do not use regex to locate or strip the
<![CDATA[...]]>delimiters; rely on a conforming XML parser.
Edge cases to handle
| Scenario | Expected return |
|---|---|
| Outer XML is malformed | "" |
target_tag not present | "" |
| CDATA section is empty or missing | "" |
| Inner content is not valid XML | "" |
attribute_name not on inner root | "" |
| Either document contains a DTD or entity declaration | "" |
What failure contract does your design guarantee, and how do you ensure the inner payload is treated with the same level of suspicion as the outer envelope?
Hints
Hint 1
A conforming XML parser unwraps CDATA automatically — after parsing, node.text is already the raw string that was between the CDATA markers. There is no need to search for or strip the <![CDATA[ and ]]> delimiters yourself.
Hint 2
Both the outer and inner documents need the same security hardening. Many candidates harden only the first parse, but the inner payload is attacker-controlled data that arrived inside the envelope — it deserves at least as much scrutiny. The two classic XML attacks (XXE and billion laughs) both require a DOCTYPE declaration, so forbidding any DTD closes both at once.
Hint 3
Python's standard library gives you expat directly via xml.parsers.expat. You can run a cheap pre-pass that installs handlers for StartDoctypeDeclHandler and EntityDeclHandler that raise immediately, then build the ElementTree only if the pre-pass succeeds. This gives you DTD rejection without a third-party dependency.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two independent parse passes and one security concern that applies to both.
Why the parser, not regex, handles CDATA
XML defines CDATA sections as a way to embed character data with markup suppressed. A conforming parser strips the <![CDATA[ and ]]> delimiters and places the raw characters in the element's .text attribute. That means after the outer parse, node.text is already the nested XML string — no substring search needed.
Using regex instead is a common mistake. It breaks on payloads that contain a literal ]]> split across sub-elements, on entity-escaped payloads (where no CDATA wrapper is present but the content is the same), and on pretty-printed documents with whitespace around the markers. Delegating to the parser handles all of these for free.
Security: why forbidding DTDs closes both attacks
Two classic XML vulnerabilities both require a <!DOCTYPE> declaration:
- XXE (XML External Entities): a crafted entity like
<!ENTITY xxe SYSTEM "file:///etc/passwd">causes the parser to read local files or make outbound HTTP requests. - Billion laughs: deeply nested internal entity references expand a few hundred bytes of input into gigabytes of memory, crashing the process.
A message-processing middleware never legitimately needs a DTD. The safest policy is to reject any document that contains one. Without a DTD, the only valid entities are the five predefined XML ones (<, &, etc.), and any other &foo; reference is a well-formedness error caught at parse time.
In production you would reach for defusedxml. The solution below shows the equivalent guarantee using only the standard library: a cheap expat pre-pass installs handlers for StartDoctypeDeclHandler and EntityDeclHandler that raise immediately. Expat propagates exceptions raised inside handlers, so parsing aborts before any entity is defined or expanded.
Failure contract
The function returns "" on every failure path and never raises. The rationale: middleware that filters a message stream should fail closed without propagating an exception up the call stack. An alternative design — raising a typed exception like ParseError — is equally valid; what matters is stating the contract explicitly before writing code.
Implementation
import xml.etree.ElementTree as ET
from xml.parsers import expat
# Defensive cap: reject absurdly large inputs before doing any work.
MAX_INPUT_CHARS = 10 * 1024 * 1024 # 10 MB
class ForbiddenXMLError(ValueError):
"""Raised when a document contains a DTD or entity declaration."""
def _forbid(*_args):
raise ForbiddenXMLError("DTDs and entity declarations are not permitted")
def _safe_fromstring(text: str) -> ET.Element:
"""
Parse XML, aborting on any DOCTYPE or entity declaration.
Raises ForbiddenXMLError, expat.ExpatError, or ET.ParseError on failure.
"""
if len(text) > MAX_INPUT_CHARS:
raise ForbiddenXMLError("input exceeds size limit")
# Pre-pass: check for forbidden constructs before building the tree.
checker = expat.ParserCreate()
checker.StartDoctypeDeclHandler = _forbid
checker.EntityDeclHandler = _forbid
checker.UnparsedEntityDeclHandler = _forbid
checker.ExternalEntityRefHandler = _forbid
checker.Parse(text, True) # raises on malformed XML or on our handlers
# Input is well-formed and DTD-free; build the element tree.
return ET.fromstring(text)
_PARSE_ERRORS = (ET.ParseError, expat.ExpatError, ForbiddenXMLError)
def extract_and_parse_nested(
xml_string: str, target_tag: str, attribute_name: str
) -> str:
if not xml_string or not target_tag or not attribute_name:
return ""
# Pass 1: parse the outer envelope.
try:
outer_root = _safe_fromstring(xml_string)
except _PARSE_ERRORS:
return ""
# iter() searches the root itself and all descendants.
node = next(outer_root.iter(target_tag), None)
if node is None:
return ""
# The parser has already unwrapped CDATA; .text is the raw nested document.
payload = (node.text or "").strip()
if not payload:
return ""
# Pass 2: parse the inner document with identical protections.
try:
inner_root = _safe_fromstring(payload)
except _PARSE_ERRORS:
return ""
return inner_root.get(attribute_name, "")
Why each decision is correct
.textnotitertext()—itertext()concatenates text from all descendants. The payload is the node's own leading text, so.textis the right accessor..strip()— pretty-printed messages often place whitespace around the CDATA block. A whitespace-only payload should short-circuit to""without a parse attempt; the strip also makes the leading-whitespace-before-root-element case valid XML.- Narrow exception catch — catching only the three known parse-error types rather than a bare
except Exceptionmeans genuine programming mistakes (e.g., aTypeErrorfrom passingNoneastarget_tag) surface during development instead of being silently swallowed. inner_root.get(attribute_name, "")—.get()returnsNoneif the attribute is absent, so the default""keeps the return type consistent.
Complexity
| Bound | |
|---|---|
| Time | O(n), where n = len(xml_string). Each document is scanned twice (pre-pass + tree build), a constant factor. |
| Space | O(n) for the outer tree, O(m ≤ n) for the inner tree. DTD rejection guarantees no entity expansion, so memory stays proportional to input. |
Common mistakes interviewers watch for
- Regex to strip CDATA delimiters. Fragile and unnecessary; let the parser do it.
- Hardening only the outer parse. The inner payload is untrusted data from the network — it needs the same treatment.
- Catching
Exceptionbroadly. Hides bugs and makes the function opaque. - Not stating the failure contract upfront. Interviewers want to see the design decision (return
""vs. raise) made explicitly, not discovered at the end. - Namespaced tags. If the outer document uses namespace prefixes, ElementTree keys the tag as
{uri}localname. The caller must pass that form, or use an XPath search likeouter_root.find('.//{uri}data'). Worth mentioning even if you don't implement it.