Parse nested XML inside CDATA
IntersystemsSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to safely extract, parse, and validate nested XML structures embedded within CDATA sections while addressing common parsing pitfalls.
Problem Statement
You are building a middleware component that processes messages from legacy systems. These messages are delivered as XML, but occasionally contain a 'payload' field where the actual data is wrapped inside a CDATA section. Critically, this CDATA block contains its own fully-formed nested XML document.
Your task is to implement a function extract_and_parse_nested(xml_string, target_tag) that performs the following steps:
- Parses the main XML to find the text content of the node specified by
target_tag. - Extracts the inner content from the CDATA section.
- Parses the extracted content into a separate XML tree.
- Returns the value of a specific attribute (e.g., 'id') from the root of the nested XML.
Constraints
- The input
xml_stringmay contain malformed XML or invalid CDATA structures. - You must handle potential XML Injection or entity expansion vulnerabilities.
- The nested XML might be empty or missing.
Function Signature
def extract_and_parse_nested(xml_string: str, target_tag: str, attribute_name: str) -> str:
# Returns the value of the attribute from the root node of the nested XML
pass
Example 1
Input:
Content]]>
target_tag = "data", attribute_name = "id"
Output: "A123"
Edge Cases
- The CDATA section is missing or empty.
- The nested content is not valid XML.
- The
target_tagdoes not exist in the root document. - The nested XML contains malicious XML External Entities (XXE).
Hints
Hint 1
Use a standard XML parser library, but ensure you explicitly disable DTD processing and external entity resolution to prevent XXE attacks.
Hint 2
Since CDATA blocks are handled by the parser during the first pass, simply accessing the node's text property should return the raw nested string.
Hint 3
Wrap your parsing logic in a try-except block to gracefully handle cases where the string inside the CDATA section is not valid XML.
Follow-up questions
- How would your approach change if the nested XML was double-encoded (e.g., entity-encoded within the CDATA)?
- What security risks arise if you allow the nested XML to include its own DTD or internal entity definitions?
- How would you optimize this if the system needs to process gigabytes of these messages per minute?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.