XML stands for eXtensible Markup Language. It is a W3C standard, text-based format for storing and exchanging structured data, in which you define your own tags (<order>, <customer>) to describe what the data means. It is “extensible” because, unlike HTML, it has no fixed set of tags.
<order> is the root element; id, sku, quantity and currency are attributes.
The XML Family of Standards
Standard
Purpose
DTD / XML Schema (XSD)
Define and validate a document’s structure and types
Namespaces
Avoid name clashes when vocabularies are mixed
XPath
Select nodes in a document
XSLT
Transform XML into other XML, HTML or text
XQuery
Query collections of XML
XML Signature / Encryption
Sign and encrypt parts of a document
Where XML Is Used Today
SOAP web services and many enterprise and government integrations.
Document formats: Office Open XML (.docx, .xlsx), OpenDocument, SVG, XHTML.
Feeds and sitemaps: RSS, Atom, sitemap.xml.
Configuration: Maven pom.xml, Android layouts, many Java and .NET configs.
Industry standards: finance (ISO 20022 payment messages), healthcare and publishing.
XML vs JSON Today
JSON is the usual choice for web APIs because it is lighter and maps directly onto programming-language objects. XML remains the better fit when you need schemas with strong validation, namespaces, mixed content (text with inline markup) or an existing XML-based standard.
Interview Tip
Expect follow-ups on well-formed vs valid XML and on DOM vs SAX parsing. Mention security too: XML parsers must have external entities disabled to prevent XXE attacks. Forgetting this is a common mistake.
2
What are the key features and benefits of XML?
KnownRevise
The key features of XML are user-defined tags, a strict tree structure, Unicode text, schema validation, namespaces and a rich set of companion standards (XPath, XSLT, XSD). Together they make XML a self-describing, platform-independent and verifiable format for exchanging structured data and documents between systems.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition) and related W3C standards
Key Features
Extensible vocabulary: you define elements such as <invoice> and <lineItem> to fit your domain.
Hierarchical structure: every document is a tree with a single root, which suits nested data.
Strict well-formedness rules: properly nested and closed tags, quoted attribute values, case-sensitive names. Parsers reject malformed input instead of guessing.
Unicode support: UTF-8 or UTF-16 by default, so any language can be represented.
Validation: DTDs or XML Schema (XSD) define allowed elements, order, data types and cardinality.
Namespaces: different vocabularies can be mixed in one document without name clashes.
Mixed content: text with inline markup (<p>Use map here</p>), which JSON handles poorly.
Separation of data and presentation: XSLT or CSS controls display; the XML holds only data.
Benefits
Benefit
What it means in practice
Interoperability
Any language and platform has mature XML parsers
Self-describing data
Tag names explain content, helpful for long-lived documents
Strong contracts
XSD validation catches bad data at system boundaries
An XSD can require isbn, define price as a decimal and allow several <author> elements, which a parser checks automatically.
Limitations to Mention
Verbose: closing tags make XML larger than JSON for the same data, which costs bandwidth and parsing time.
More complex: namespaces, schemas and entity rules add a learning curve.
Security: DTD processing enables XXE and “billion laughs” attacks if the parser is not configured safely.
Awkward mapping to objects: the attribute vs element choice and mixed content do not map neatly onto data structures.
When to Choose XML
Choose XML when you need validated contracts, document-style content, namespaces or an existing XML standard. For simple web APIs between your own services, JSON is usually simpler and faster.
Interview Tip
Interviewers like a balanced answer. A common mistake is calling XML obsolete; it is still central to office formats, SOAP-based enterprise integration, financial messaging and sitemaps.
3
What is the difference between XML and HTML?
KnownRevise
XML is designed to describe and transport data with tags you define yourself, and it follows strict syntax rules. HTML is designed to display content in a browser using a fixed set of predefined tags, and browsers tolerate and repair many syntax errors. XML says what the data is; HTML says how the page is structured for presentation.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition) and the HTML Living Standard (WHATWG)
Comparison
Aspect
XML
HTML
Purpose
Store and exchange data
Structure and display web pages
Tags
User-defined (<invoice>)
Predefined (<p>, <div>, <table>)
Syntax strictness
Must be well-formed, or the parser stops with an error
Forgiving; browsers fix many errors
Closing tags
Always required (or self-closing <tag/>)
Optional for some elements (<li>, <p>); void elements like <br> have none
The XML tells a program that 19.99 is a price in USD; the HTML only tells a browser to show a heading and a paragraph.
How They Relate
Both come from SGML, the older markup standard.
XHTML is HTML written as well-formed XML. HTML5 has an XML serialization too, but most pages use the HTML syntax.
XML data is often converted to HTML for display, for example with XSLT on a server.
When You Use Each
XML: configuration files, SOAP messages, RSS feeds, sitemaps, SVG graphics, office documents, data exchange between systems.
HTML: web pages and the user interfaces of web applications.
Interview Tip
The key points are purpose (data vs presentation), predefined vs custom tags, and strict vs forgiving parsing. A common mistake is saying XML “replaces” HTML; they solve different problems and are often used together.
4
What are the main components of an XML document?
KnownRevise
An XML document is a text document that follows XML’s well-formedness rules. Its main components are an optional prolog (XML declaration, comments, processing instructions and a document type declaration), exactly one root element containing nested elements, attributes and text, and optionally comments, processing instructions, CDATA sections and entity references throughout.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
The Components
XML declaration (optional, must come first): <?xml version="1.0" encoding="UTF-8"?>, giving the version and character encoding.
Document type declaration (optional): <!DOCTYPE ...> that links or embeds a DTD.
Root element: the single top-level element that contains everything else.
Elements: start tag, content and end tag (<name>...</name>), or an empty element <br/>.
Attributes: name-value pairs in the start tag (id="42"), giving metadata about the element.
Text content: character data inside elements.
Entity and character references: &, <, © for special or non-typeable characters.
CDATA sections: <![CDATA[ ... ]]> for text that should not be parsed as markup.
Comments: <!-- ... -->.
Processing instructions: <?xml-stylesheet type="text/xsl" href="style.xsl"?>, instructions for applications.
Annotated Example
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="orders.xsl"?>
<!DOCTYPE orders SYSTEM "orders.dtd">
<!-- Daily order export -->
<orders date="2026-11-04">
<order id="1042">
<customer>Ravi & Sons</customer>
<note><![CDATA[Deliver before 5 pm & call <reception>]]></note>
<total currency="INR">2450.00</total>
</order>
</orders>
Line
Component
<?xml ...?>
XML declaration
<?xml-stylesheet ...?>
Processing instruction
<!DOCTYPE ...>
Document type declaration
<!-- ... -->
Comment
<orders>
Root element with attribute date
&
Entity reference for &
<![CDATA[...]]>
CDATA section
Structural Rules
Exactly one root element.
Elements must be properly nested: <a></a>, never <a></a>.
Every start tag has a matching end tag, or the element is self-closing.
Attribute values are quoted, and an element cannot repeat an attribute.
Names are case-sensitive.
The Tree View
Parsers see the document as a tree of nodes: document, element, attribute, text, comment and processing-instruction nodes. XPath and the DOM work on this tree, which is why understanding the components matters for querying and transforming XML.
Interview Tip
A common mistake is thinking the XML declaration is a processing instruction. It looks like one but is a separate construct, and if present it must be the very first thing in the file, with nothing before it, not even whitespace.
5
What is the structure of an XML element?
KnownRevise
An XML element consists of a start tag (with the element name and optional attributes), its content (text, child elements, or both) and a matching end tag, for example <price currency="USD">19.99</price>. An element with no content can be written as an empty-element tag such as <br/>.
<divider/> and <divider></divider> are equivalent in XML: both are elements with no content.
Rules for Elements
Names are case-sensitive and must start with a letter or underscore (or another allowed name-start character). They cannot contain spaces and should not begin with xml in any case, which is reserved.
Every start tag needs an end tag (unless it is an empty-element tag).
Proper nesting: an element that opens inside another must close inside it.
Attributes: values always quoted (single or double quotes); no duplicate attribute names on one element.
Special characters in content are escaped: < for < and & for &.
Elements in the Document Tree
Elements form a hierarchy:
the root element contains everything;
an element’s direct children are its child elements, and the containing element is their parent;
elements with the same parent are siblings.
This tree is what XPath navigates (/order/item[@sku='BK-17']) and what DOM APIs expose.
Example: Reading an Element in Python
import xml.etree.ElementTree as ET
xml_text = '<item sku="BK-17" quantity="2">System Design Handbook</item>'
item = ET.fromstring(xml_text)
print(item.tag) # item
print(item.attrib["sku"]) # BK-17
print(int(item.get("quantity"))) # 2
print(item.text) # System Design Handbook
Interview Tip
Interviewers often follow up with “element or attribute?”. Use elements for data that can repeat, has structure or may be extended later, and attributes for simple metadata such as IDs or units. Mismatched case in tags (<Item>...</item>) is a classic well-formedness error.
6
What is the purpose of XML attributes?
KnownRevise
XML attributes are name-value pairs inside an element’s start tag (<price currency="USD">) that add metadata about the element, such as an identifier, a unit, a type or a language. They describe the element rather than forming its main content, which usually goes in child elements or text.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), XML Schema 1.0/1.1
Syntax Rules
Written in the start tag: <order id="1042" status="paid">.
Values must always be quoted (single or double quotes).
An attribute name can appear only once per element.
Order of attributes is not significant.
Values are plain text: no child elements, and < and & must be escaped (<, &).
Typical Uses
Identifiers: id="p42", ref="p42"
Units and formats: currency="INR", unit="kg"
Language: the built-in xml:lang="en"
Type or classification: type="express"
Namespace declarations: xmlns="...", xmlns:x="..." look like attributes
Flags: deprecated="true"
Attributes vs Elements
Aspect
Attribute
Child element
Repeats
No (once per element)
Yes
Structure
Plain text value only
Can contain nested elements
Order
Not preserved as meaningful
Order is preserved
Extensibility
Hard to extend later
Easy to add sub-elements
Best for
Metadata, IDs, units
Main data, lists, rich content
The same data both ways:
<!-- Attribute style: metadata on the element -->
<price currency="USD">19.99</price>
<!-- Element style: structured data -->
<price>
<amount>19.99</amount>
<currency>USD</currency>
</price>
Attributes in Schemas
XML Schema can declare attributes with types, defaults and whether they are required:
DTDs can also declare ID and IDREF attributes for cross-references inside a document.
Reading Attributes in Python
import xml.etree.ElementTree as ET
price = ET.fromstring('<price currency="USD">19.99</price>')
print(price.get("currency")) # USD
print(price.get("discount", "none")) # default when the attribute is missing
print(float(price.text)) # 19.99
Best Practices
Use attributes for simple, single-valued metadata; use elements for data that may grow, repeat or contain structure.
Keep naming consistent (for example lowerCamelCase throughout).
Do not hide lists in attributes (colors="red,blue"); use repeated elements so schemas and XPath can work with them.
Interview Tip
A common mistake is putting everything in attributes to make documents shorter; it makes the format hard to extend. Mention that xml:lang and xml:space are reserved attributes defined by the XML specification.
7
What are XML namespaces and why are they used?
KnownRevise
XML namespaces give element and attribute names a unique identity by associating them with a namespace URI, so names from different vocabularies can be mixed in one document without clashing. For example, a <table> from an HTML vocabulary and a <table> from a furniture catalogue can coexist because each belongs to a different namespace.
Read full answerHide full answer
Applies toNamespaces in XML 1.0 (Third Edition, W3C 2009)
The Problem
Two vocabularies both define <title>: a book catalogue and an HR system (job title). When a document combines them, software cannot tell which <title> is which.
How Namespaces Work
A namespace is identified by a URI, for example http://example.com/books. It is only an identifier; parsers never fetch it.
You declare it with xmlns (default namespace) or xmlns:prefix (prefixed namespace).
A name’s identity becomes the pair (namespace URI, local name). The prefix is only a shorthand.
Querying without the namespace: find("title") returns nothing when the document has a default namespace. This is the most common namespace bug.
Assuming the URI is a web address to download: it does not need to resolve.
Comparing prefixes instead of URIs in custom code.
Interview Tip
Explain that the URI, not the prefix, defines identity, and that the default namespace does not apply to attributes. Interviewers often ask why an XPath query “finds nothing”, and the answer is usually a default namespace.
8
What is the difference between well-formed and valid XML?
KnownRevise
Well-formed XML follows the basic syntax rules of the XML specification (one root, properly nested and closed tags, quoted attributes, escaped special characters), so any XML parser can read it. Valid XML is well-formed and conforms to a schema, either a DTD or an XML Schema (XSD), that defines which elements, attributes, order and data types are allowed. Every valid document is well-formed, but not every well-formed document is valid.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), XML Schema 1.0/1.1
Well-Formedness Rules
Exactly one root element.
Every start tag has a matching end tag, or the element is self-closing (<br/>).
Elements are properly nested.
Tag names match exactly, including case.
Attribute values are quoted, and no attribute is repeated on an element.
< and & in text are escaped as < and &.
The XML declaration, if present, is the very first thing in the document.
If a document breaks any of these, it is not XML at all: the parser must report a fatal error and stop.
Validity
A valid document also matches its schema, for example:
<order> must contain exactly one <customer> and one or more <item>.
quantity must be a positive integer.
id is required.
Example
<!-- Well-formed, but invalid if the schema requires quantity to be an integer -->
<order id="1042">
<item sku="BK-17" quantity="two">Handbook</item>
</order>
<!-- Not well-formed: tags are not properly nested -->
<order><item>Handbook</order></item>
Comparison
Aspect
Well-formed
Valid
Checks
XML syntax
Syntax + structure and types
Needs a schema
No
Yes (DTD or XSD)
Who checks
Every XML parser
A validating parser or validator
On failure
Fatal error; document rejected
Validation errors; the application decides
Guarantees
Can be parsed into a tree
Data matches the agreed contract
Checking in Python
The standard library checks well-formedness; validation against an XSD needs a library such as lxml.
Contract enforcement: reject bad input at the system boundary instead of failing deep in business logic.
Interoperability: partners agree on an XSD (common in banking, healthcare and government integrations).
Code generation: tools such as JAXB generate classes from the schema.
Interview Tip
A common mistake is treating “valid” and “well-formed” as synonyms. Also mention security: when validating with DTDs, disable external entity resolution to avoid XXE attacks.
9
What does the XML declaration do in an XML document?
KnownRevise
The XML declaration (<?xml version="1.0" encoding="UTF-8"?>) is an optional line at the very start of a document that tells the parser which XML version the document uses, which character encoding it is written in, and optionally whether it is standalone (does not depend on an external DTD for its content).
Character encoding, e.g. UTF-8, UTF-16, ISO-8859-1
standalone
No
yes = no external markup declarations affect the content; default no
The pseudo-attributes must appear in this order: version, then encoding, then standalone.
Rules
If present, it must be the very first thing in the file: no whitespace, comments or blank lines before it. (A UTF-8 byte order mark is allowed before it.)
It may appear only once.
Despite its <?...?> look, it is not a processing instruction; it is a separate construct, and xml is reserved as a processing-instruction target.
Why It Matters
Encoding detection: a parser reads the first bytes to guess the encoding family, then uses the declared encoding to decode the rest. Without a declaration, the parser assumes UTF-8 or UTF-16 (detected from a byte order mark).
Avoiding corrupted text: if a file is saved in ISO-8859-1 but read as UTF-8, characters such as é become garbage or cause errors. Declaring the real encoding prevents that.
Version selection: XML 1.1 allows a few more characters in names and some control characters; it is rarely used, and many tools only support 1.0.
standalone="yes" lets a non-validating parser know it can skip fetching external DTDs without changing the document’s meaning.
When Is It Required?
The declaration is optional for XML 1.0 documents in UTF-8 or UTF-16. It is required when:
the document uses an encoding other than UTF-8 or UTF-16, or
the document is XML 1.1.
Including it is still good practice, because it makes the encoding explicit.
If this file is really saved as UTF-8, the ü bytes are decoded wrongly. Keep the declared encoding and the actual file encoding the same; UTF-8 everywhere is the simplest rule.
Interview Tip
Common follow-ups: “Can you put a comment before the declaration?” (no), and “Is the declaration a processing instruction?” (no). A common mistake is setting standalone="yes" while the document relies on default attribute values from an external DTD.
10
What are XML entities and how are they used?
KnownRevise
XML entities are named units of content that a parser replaces with their value. The most common are the five predefined entities (<, >, &, ", ') for escaping special characters, plus character references (©) and user-defined entities declared in a DTD for reusable text or external content.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
Predefined Entities
Entity
Character
When needed
<
<
Always in text (would start a tag)
&
&
Always in text (would start a reference)
>
>
Needed only in the sequence ]]> but often escaped anyway
External entity, whose content comes from a file or URL:
<!ENTITY terms SYSTEM "terms.xml">
Parameter entities (<!ENTITY % name "...">, used as %name;) are used only inside DTDs, to reuse parts of declarations.
Security Risks
User-defined entities are the source of two well-known attacks:
XXE (XML External Entity): an attacker declares <!ENTITY x SYSTEM "file:///etc/passwd"> and references &x;. A parser that resolves external entities may leak local files or make requests to internal servers (SSRF).
Billion laughs (entity expansion): nested entities that each expand to ten copies of the previous one grow a tiny document into gigabytes of text, exhausting memory.
Fix: disable DTD processing or at least external entities in the parser, and limit entity expansion. In Java, set the http://apache.org/xml/features/disallow-doctype-decl feature to true; in Python, use the defusedxml package for untrusted input.
Escaping in Code
Libraries escape automatically when you build XML properly:
import xml.etree.ElementTree as ET
el = ET.Element("condition")
el.text = "price < 100 && stock > 0"
print(ET.tostring(el, encoding="unicode"))
# <condition>price < 100 && stock > 0</condition>
Best Practices
Build XML with a library, not by string concatenation, so escaping is never forgotten.
Use UTF-8 and type characters directly instead of many character references.
Never let untrusted documents declare entities.
Interview Tip
Interviewers almost always connect entities to XXE. Explaining both the attack and the parser configuration that prevents it is what separates a strong answer from a definition.
11
What are the naming rules for XML elements and attributes?
KnownRevise
XML element and attribute names must start with a letter, an underscore (_) or a colon, and may then contain letters, digits, hyphens, underscores and periods. They are case-sensitive, cannot contain spaces, and names beginning with xml (in any combination of case) are reserved. The colon is reserved for namespace prefixes in practice.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), Namespaces in XML 1.0
The Rules
First character: a letter (any Unicode letter, not only A–Z), _, or :. Never a digit, hyphen or period.
Other characters: letters, digits, -, _, ., plus some combining characters.
No whitespace anywhere in a name.
No other punctuation: !, @, #, $, %, &, *, /, (, ) and so on are not allowed.
Case-sensitive: <Order>, <order> and <ORDER> are three different elements, and the end tag must match exactly.
Reserved prefix: names beginning with xml, XML, Xml and so on are reserved for W3C standards (for example xml:lang).
Colons: technically allowed, but with namespaces a colon separates prefix and local name (hr:employee), so do not use it otherwise.
Attributes: same rules, and an attribute name may appear only once per element.
Valid and Invalid Examples
Name
Valid?
Reason
firstName
Yes
Letters only
first_name
Yes
Underscore allowed
first-name
Yes
Hyphen allowed after the first character
_id
Yes
Can start with underscore
order.v2
Yes
Period allowed after the first character
名前
Yes
Unicode letters allowed
2ndAddress
No
Starts with a digit
first name
No
Contains a space
-total
No
Starts with a hyphen
price$
No
$ not allowed
xmlData
Reserved
Starts with xml
Checking in Python
import xml.etree.ElementTree as ET
for name in ["first_name", "2ndAddress", "first name"]:
try:
ET.fromstring(f"<{name}>x</{name}>")
print(name, "-> ok")
except ET.ParseError:
print(name, "-> invalid")
Naming Best Practices
Be descriptive: <shippingAddress> rather than <sa>.
Pick one convention and keep it everywhere: lowerCamelCase (orderDate), kebab-case (order-date) or snake_case.
Avoid hyphens if the XML is mapped to code: some tools turn names into variables where - is not allowed.
Avoid periods in names, since some tools treat them as object paths.
Do not encode data in names: use <item type="book"> instead of <bookItem>, <dvdItem>.
Keep names stable: renaming an element breaks every schema, XPath and consumer that uses it.
Interview Tip
The common mistakes are names starting with a digit and mismatched case between start and end tags. Mention that Unicode letters are allowed, which many candidates forget.
12
When should you use XML elements versus attributes?
KnownRevise
Elements hold the main data of a document and can contain text, child elements, or both; they can repeat and keep their order. Attributes are name-value pairs inside a start tag that hold simple metadata about an element (an ID, a unit, a language); each appears at most once and can only contain text. Use elements for content and structure, attributes for short, single-valued properties.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), XML Schema 1.0/1.1
Comparison
Aspect
Element
Attribute
Content
Text, child elements, mixed content
Plain text value only
Repetition
Can repeat (<phone> twice)
At most once per element
Order
Preserved and meaningful
Not significant
Structure
Can nest and grow
Flat; cannot be extended with sub-parts
Whitespace
Preserved
Normalized (newlines and tabs become spaces)
Schema support
Full: types, order, cardinality
Types, required/optional, defaults
Readability
More verbose
Compact
The Same Data Both Ways
<!-- Attributes for metadata, elements for content -->
<book id="b42" lang="en">
<title>Designing Data Systems</title>
<author>A. Sharma</author>
<author>R. Iyer</author>
<price currency="USD">39.99</price>
</book>
<!-- Over-using attributes: cannot hold two authors, hard to extend -->
<book id="b42" lang="en" title="Designing Data Systems"
author="A. Sharma" price="39.99" currency="USD"/>
Guidelines
Use an element when:
the value can repeat (authors, phone numbers, line items);
it has or may later have structure (an address with street, city, PIN);
it is the document’s main content, or contains long or rich text;
order matters.
Use an attribute when:
it is metadata describing the element: id, type, version, status;
it qualifies the content: currency="USD", unit="kg", xml:lang="en";
it is a short value from a fixed set (an enumeration) that will never need sub-parts.
Practical Effects
XPath: elements are selected with /book/author, attributes with /book/@id.
Data binding (JAXB, .NET serializers) can map both, but repeated values must be elements.
Schema evolution: adding a child element to a former attribute value forces a breaking change, so choose carefully at the start.
Interview Tip
There is no single correct answer, so explain the criteria: repetition, structure, extensibility and metadata vs content. A common mistake is choosing attributes just to make documents shorter, which makes the format hard to extend later.
13
How are comments written in XML and what are they for?
KnownRevise
XML comments are notes for human readers, written between <!-- and -->, for example <!-- Prices are in INR -->. Parsers do not treat them as data: they are not part of the element content, and most applications ignore them, although many APIs can still read them as comment nodes.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
Syntax
<?xml version="1.0" encoding="UTF-8"?>
<!-- Order export generated nightly -->
<orders>
<!-- Each order lists its items in the order they were added -->
<order id="1042">
<total currency="INR">2450.00</total>
</order>
<!--
Multi-line comments are allowed.
<order id="1043"> ... </order> (temporarily disabled)
-->
</orders>
Rules
A comment starts with <!-- and ends with -->.
The string -- (two hyphens) must not appear inside a comment, and a comment cannot end with --->.
Comments cannot be nested.
Comments cannot appear inside a tag: <item <!-- note --> sku="1"> is not well-formed.
They can appear anywhere else: before or after the root element, between elements, inside content, and after the XML declaration (never before it).
Text inside a comment is not parsed: <, & and tags inside it are just text.
Uses
Documentation: explaining the meaning of fields, units or business rules in configuration files (pom.xml, Spring XML, Android manifests).
Temporarily disabling content: commenting out a configuration block while testing.
Generation notes: “generated by tool X, do not edit”.
Schema documentation: in XSD files, prefer <xs:annotation><xs:documentation>, which tools can read and publish.
Comments in Code
Python’s ElementTree drops comments by default; a parser with a TreeBuilder that keeps them can read them:
import xml.etree.ElementTree as ET
text = "<config><!-- port for local dev --><port>8080</port></config>"
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
root = ET.fromstring(text, parser=parser)
for node in root:
if node.tag is ET.Comment:
print("comment:", node.text.strip())
else:
print(node.tag, node.text)
Best Practices and Pitfalls
Never put data in comments that a program needs; it may be stripped by transformations, canonicalization or minification.
Do not put secrets in comments: they are sent and stored with the document.
Comments are excluded by default in Canonical XML used for signatures (the “without comments” variant), so they do not affect signature checks there.
Watch for -- in comment text, such as a command-line flag --verbose, which makes the document not well-formed.
Interview Tip
The detail interviewers look for is the -- restriction and the fact that comments are not part of the data. A common mistake is using comments to pass instructions to an application; processing instructions exist for that.
14
What are processing instructions in XML?
KnownRevise
Processing instructions (PIs) are markup that passes instructions to an application, rather than data to the document’s content. They are written as <?target data?>, for example <?xml-stylesheet type="text/xsl" href="report.xsl"?>, where the target names the application or purpose and the rest is free-form data for it.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
Syntax
<?target instruction-data?>
The target is a name that identifies who the instruction is for.
The data is any text except the closing ?>; its format is up to the application. Many PIs use an attribute-like style (type="..." href="..."), but those are not real attributes.
Targets starting with xml (any case) are reserved; xml-stylesheet is a W3C-standardized PI.
<?xml version="1.0"?> looks like a processing instruction but is a separate construct, which is why the target xml is reserved.
How Applications See Them
Parsers report PIs as separate nodes (DOM ProcessingInstruction nodes, SAX processingInstruction(target, data) callbacks, XPath processing-instruction()). Applications that do not recognize a target ignore it.
import xml.etree.ElementTree as ET
text = '<invoice><?page-break?><total>4200</total></invoice>'
parser = ET.XMLParser(target=ET.TreeBuilder(insert_pis=True))
root = ET.fromstring(text, parser=parser)
for node in root:
if node.tag is ET.ProcessingInstruction:
print("PI:", node.text) # PI: page-break
PIs vs Comments vs Elements
Comments are for humans and should be ignored by programs.
PIs are for programs, but sit outside the document’s data model.
Elements and attributes are the data itself.
Best Practices
Use PIs sparingly; information the application really needs usually belongs in elements, attributes or schemas.
Do not rely on PIs surviving every transformation; some tools drop them.
Interview Tip
The standard example to give is xml-stylesheet. A common mistake is calling the XML declaration a processing instruction.
15
Is there a difference between an empty element and a self-closing element in XML?
KnownRevise
In XML there is no semantic difference: <br></br> and <br/> both represent an empty element, one with no content. The self-closing form (<tag/>, called an empty-element tag) is just a shorter syntax for a start tag immediately followed by its end tag. Parsers produce the same tree for both.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
The Two Forms
<!-- Start tag + end tag with nothing between -->
<divider></divider>
<!-- Empty-element (self-closing) tag -->
<divider/>
<!-- Both can carry attributes -->
<image src="logo.png" width="120" height="40"/>
Important Details
Nothing between the tags: <divider> </divider> contains a space, so it has one whitespace text node. A schema that requires an empty element may reject it, and some APIs return " " instead of no text.
Empty vs absent: an empty element is present with no value; an absent element does not appear at all. These often mean different things, for example “middle name is empty” vs “middle name not provided”.
Empty vs nil: XML Schema can mark an element as explicitly null with xsi:nil="true", distinct from an empty string.
The space before the slash (<br />) is optional in XML; it was a convention for compatibility with old HTML browsers.
Equivalence in Code
import xml.etree.ElementTree as ET
a = ET.fromstring("<divider></divider>")
b = ET.fromstring("<divider/>")
c = ET.fromstring("<divider> </divider>")
print(a.text, b.text) # None None -> identical empty elements
print(repr(c.text)) # ' ' -> not empty: contains whitespace
print(ET.tostring(a)) # b'<divider />' (serializer picks the short form)
Schema View
In XSD, an element is required to be empty by giving it a complex type with no content:
The equivalence is an XML rule. In HTML (not XHTML), only void elements such as <br>, <img> and <input> have no end tag, and a trailing slash on a non-void element is ignored: <div/> in HTML opens a <div> that is never closed. This is a classic bug when XML-style markup is served as HTML.
Interview Tip
State clearly that they are equivalent in XML, then mention the edge cases interviewers like: whitespace makes an element non-empty, empty vs missing vs xsi:nil, and the different behaviour in HTML.
16
What are CDATA sections in XML and when should you use them?
KnownRevise
A CDATA section (<![CDATA[ ... ]]>) marks a block of text that the parser treats as literal character data, not markup. Characters such as < and & inside it need no escaping, which is convenient for embedding code snippets, HTML fragments or other text full of special characters.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
Syntax
<snippet language="javascript"><![CDATA[
if (a < b && b > c) {
console.log("<done>");
}
]]></snippet>
Without CDATA, the same content needs escaping:
<snippet>if (a < b && b > c) { console.log("<done>"); }</snippet>
Both forms produce the same text for the application.
Rules
Starts with <![CDATA[ and ends with the first ]]>.
The sequence ]]>cannot appear inside a CDATA section. To include it, split the section: <![CDATA[ ...]]]]><![CDATA[>... ]]>.
CDATA sections cannot be nested.
They can appear only in element content, not in attribute values and not outside the root element.
Entities and character references are not expanded inside CDATA: & stays as the five characters &.
When to Use CDATA
Embedding source code, SQL or regular expressions with many <, > and & characters.
Embedding HTML or another markup as opaque text inside an XML message (for example an RSS <description>).
Hand-written configuration files where escaping would hurt readability.
When Not to Use It
Binary data: CDATA cannot hold arbitrary bytes or control characters; use Base64 in a normal element (xs:base64Binary).
Data that programs generate: libraries escape text automatically, so CDATA adds nothing.
As a security measure: CDATA does not sanitize anything. HTML stored in CDATA and later inserted into a web page can still cause XSS.
Expecting it to survive: CDATA is purely lexical. Parsers report it as ordinary text, and most serializers or canonicalization steps write the text back with escaping, so the CDATA wrapper disappears.
Reading CDATA in Python
import xml.etree.ElementTree as ET
doc = ET.fromstring("<snippet><![CDATA[if (a < b && c) { }]]></snippet>")
print(doc.text) # if (a < b && c) { }
print(ET.tostring(doc, encoding="unicode")) # <snippet>if (a < b && c) { }</snippet>
The output shows that the CDATA wrapper is not kept: the text is the same, written with escapes.
Interview Tip
Key points: CDATA changes only how text is written, not what it means; ]]> cannot appear inside it; and it is not for binary data or sanitization. A common mistake is assuming an application can tell CDATA text from escaped text; in the data model they are identical.
17
What is the XML prolog and what does it contain?
KnownRevise
The XML prolog is everything in a document before the root element. It can contain the XML declaration, a document type declaration (<!DOCTYPE>), and any number of comments, processing instructions and whitespace. All of it is optional, but if the XML declaration is present it must come first.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition)
What the Prolog Can Contain
Part
Example
Purpose
XML declaration
<?xml version="1.0" encoding="UTF-8"?>
Version, encoding, standalone status
Comments
<!-- exported nightly -->
Notes for humans
Processing instructions
<?xml-stylesheet type="text/xsl" href="r.xsl"?>
Instructions for applications
Document type declaration
<!DOCTYPE catalog SYSTEM "catalog.dtd">
Links or embeds a DTD
Order Rules
The XML declaration, if present, must be the very first thing in the file.
Then any comments, processing instructions and whitespace.
At most one<!DOCTYPE>, which must come before the root element.
More comments and processing instructions may follow the DOCTYPE.
External DTD: <!DOCTYPE catalog SYSTEM "catalog.dtd"> or with a public identifier (PUBLIC "..." "...").
Internal subset: declarations inside [ ... ], as in the example.
It can declare elements, attributes, default values and entities.
Security Note
The DOCTYPE is where XXE and entity-expansion (“billion laughs”) attacks are defined. For untrusted input, configure the parser to reject DOCTYPE declarations or at least disable external entities. Most modern documents validated with XSD do not need a DOCTYPE at all.
What Is Not in the Prolog
The XSD link (xsi:schemaLocation) is an attribute on the root element, not part of the prolog.
Comments and processing instructions after the root element form the document’s epilog (the spec calls it Misc content).
Interview Tip
Expect “what must be first?” (the XML declaration, if present) and “how many DOCTYPEs?” (at most one). Mentioning the DOCTYPE’s security implications is a strong addition.
18
What are XML character references and how are they used?
So in XML you write   or   instead of , or simply type the character in UTF-8.
Where They Can Be Used
In element text and attribute values: <price note="₹ incl. tax">499</price>.
Not in element or attribute names, and not inside CDATA sections or comments, where they are not expanded.
Restrictions
A character reference must refer to a character allowed in XML. In XML 1.0, � and most control characters (such as –) are not allowed, even as references, so a document containing them is not well-formed. Tab (	), line feed ( ) and carriage return ( ) are allowed.
Common Uses
Characters outside the document’s declared encoding (for example € in an ISO-8859-1 file).
Invisible or ambiguous characters: non-breaking space, zero-width joiner, right-to-left marks.
Preserving whitespace in attributes: attribute normalization turns literal tabs and newlines into spaces, but survives as a real newline.
Escaping < or & (though < and & are more readable).
The parser resolves the references, so the application sees the real characters.
Best Practices
Use UTF-8 and type characters directly when possible; documents are easier to read.
Use references for invisible characters, so a reader can see they are there.
Do not use HTML named entities in XML without declaring them.
Interview Tip
A common mistake is using in XML and getting a parser error (“undefined entity”). Explain the difference between character references and entity references, and that � is never allowed in XML 1.0.
19
What is the difference between an XML document and an XML fragment?
KnownRevise
An XML document is a complete, well-formed unit: it has exactly one root element and may have a prolog (XML declaration, DOCTYPE, comments). An XML fragment is a piece of XML, such as several sibling elements or mixed text and elements, that is not a complete document on its own, usually because it has no single root or no prolog. Fragments are parsed inside a context, or wrapped in a root, to be processed.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition); XML Fragment Interchange (W3C Candidate Recommendation)
Pieces of a document, template parts, query results, streams
Where Fragments Appear
XPath and XQuery results: a query returns a sequence of nodes, not a document.
Streaming logs and feeds: a file with one <event> per line has no single root.
Databases: SQL Server’s xml type and other XML columns can store fragments.
Templates and SOAP bodies: content inserted into a larger document.
DOM: DocumentFragment nodes group nodes before inserting them into a tree.
Parsing a Fragment
Standard parsers reject multiple roots (“junk after document element”). The simple fix is to wrap the fragment in a temporary root:
import xml.etree.ElementTree as ET
fragment = '<order id="1"/><order id="2"/>'
try:
ET.fromstring(fragment)
except ET.ParseError as e:
print("not a document:", e)
root = ET.fromstring(f"<wrapper>{fragment}</wrapper>")
print([o.get("id") for o in root]) # ['1', '2']
Some APIs support fragments directly, for example .NET’s XmlReader with ConformanceLevel.Fragment.
Pitfalls
Wrapping changes namespaces: if the fragment uses prefixes declared in its original document, the wrapper must declare them too.
Entities: a fragment cannot rely on a DTD that is not present.
Encoding: without a declaration, the fragment is assumed to be UTF-8 or UTF-16.
Interview Tip
The key test is “one root element”. A common follow-up is how to parse a log with many top-level elements; wrapping in a root, or a streaming parser that accepts fragments, is the expected answer.
20
How does XML handle whitespace?
KnownRevise
An XML parser passes all whitespace in element content to the application: spaces, tabs and line breaks between and inside elements are kept as text. What happens next depends on the context: line endings are normalized to a single line feed, attribute values are normalized (tabs and newlines become spaces), whitespace in a DTD-declared element-only content model is reported as ignorable, and xml:space="preserve" signals that whitespace matters.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), XML Schema 1.0/1.1
What Counts as Whitespace
XML whitespace is space (#x20), tab (#x9), line feed (#xA) and carriage return (#xD).
The Rules
Line-ending normalization: \r\n and lone \r are converted to \n before parsing, on every platform.
Element content: whitespace is preserved and reported as text. Indentation in a pretty-printed file becomes whitespace-only text nodes between elements.
Attribute-value normalization: literal tabs, newlines and carriage returns in an attribute value become spaces. For attributes declared with a non-CDATA type (such as ID or NMTOKENS) in a DTD, leading and trailing spaces are also removed and runs of spaces collapsed.
Ignorable whitespace: with a DTD that declares element-only content, validating parsers can tell applications that whitespace between elements is ignorable (SAX ignorableWhitespace).
xml:space: xml:space="preserve" tells applications to keep whitespace exactly; default lets them apply their own rules. It is a signal, not something parsers enforce.
XML Schema whiteSpace facet: during validation, values are processed with preserve, replace (tabs and newlines become spaces) or collapse (also trims and collapses runs). Most built-in types such as xs:int and xs:token use collapse, so <qty> 5 </qty> is a valid integer.
Example
import xml.etree.ElementTree as ET
doc = ET.fromstring("<order>\n <qty> 5 </qty>\n <note a='x\ty'>Hi</note>\n</order>")
print(repr(doc.text)) # '\n ' indentation is a text node
print(repr(doc.find("qty").text)) # ' 5 ' kept as written
print(int(doc.find("qty").text)) # 5 trimming is the application's job
print(repr(doc.find("note").get("a"))) # 'x y' tab normalized to a space
Practical Consequences
DOM child counts include whitespace text nodes, so firstChild of <order> may be a text node, not <qty>. Use element-only navigation (firstElementChild, XPath *).
XPathnormalize-space() trims and collapses whitespace when comparing text.
XSLT can remove whitespace-only text nodes with <xsl:strip-space elements="*"/>.
Signatures: whitespace changes the bytes being signed, so pretty-printing a signed document breaks its signature.
Mixed content such as <p>Hello world</p> depends on whitespace; never strip it there.
Interview Tip
The common mistake is assuming parsers ignore indentation. They do not; the application or schema decides. Mention line-ending normalization and attribute normalization as the two things the parser itself always does.
21
What is XML Schema (XSD) and what is it used for?
KnownRevise
XML Schema, usually called XSD (XML Schema Definition), is a W3C language for describing the structure, content and data types an XML document must follow. A schema is itself an XML document that defines which elements and attributes are allowed, their order and number, and their types (integer, date, decimal with 2 places, enumeration). Validating a document against the XSD checks that it meets that contract.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 (widely supported) and 1.1 (adds assertions; supported by Xerces-J and Saxon-EE)
What a Schema Defines
Elements and attributes that may appear, and where.
Structure: order (xs:sequence), choices (xs:choice), nesting.
Cardinality: minOccurs and maxOccurs.
Data types: about 44 built-in types (xs:string, xs:int, xs:decimal, xs:date, xs:boolean, xs:anyURI), plus custom types.
A document with quantity="two" or no <customer> fails validation.
What It Is Used For
Contracts between systems: partners exchange an XSD that defines exactly what messages look like (SOAP/WSDL services, banking ISO 20022, healthcare, government filings).
Input validation at system boundaries, rejecting bad data before business logic.
Code generation: JAXB (xjc), .NET xsd.exe and other tools generate classes from the schema.
Editor support: IDEs use the XSD for autocompletion and inline errors.
Documentation of a format, using xs:annotation.
XSD vs DTD (briefly)
XSD is written in XML, supports namespaces and real data types, and has richer constraints. DTDs are simpler and older, only know text, and can declare entities. Most modern XML formats use XSD (or RELAX NG).
Limitations
Verbose and complex for large formats.
Limited co-constraints in XSD 1.0 (for example “if type is X then field Y is required”); XSD 1.1 assertions or Schematron cover these.
Validation cost: validating large documents takes CPU time, so some systems validate only at the edge.
Interview Tip
Connect XSD to the difference between well-formed and valid XML, and give a concrete use: validating partner messages at an API boundary. A common mistake is believing the parser fetches xsi:schemaLocation automatically; validation must be enabled and configured.
22
What is the difference between a DTD and an XML Schema?
KnownRevise
A DTD (Document Type Definition) and an XML Schema (XSD) both define the allowed structure of XML documents, but a DTD uses its own non-XML syntax and can only describe structure and text content, while XSD is written in XML, supports namespaces and has real data types (integers, dates, decimals, patterns). XSD is the usual choice for data exchange today; DTDs survive in older formats and for entity declarations.
The DTD accepts quantity="lots"; the XSD only accepts positive integers.
Comparison
Aspect
DTD
XML Schema (XSD)
Syntax
Special DTD syntax
XML
Data types
Text only (#PCDATA, CDATA, plus ID, IDREF, NMTOKEN, enumerations for attributes)
About 44 built-in types plus custom types
Namespaces
Not supported
Fully supported (targetNamespace)
Facets (length, pattern, range)
No
Yes
Cardinality
?, *, + only
Exact minOccurs / maxOccurs
Type reuse and inheritance
No
Extension and restriction of types
Uniqueness and keys
ID/IDREF only (document-wide)
xs:key, xs:unique, xs:keyref scoped by XPath
Entities
Yes (declares entities)
No
Defaults
Attribute defaults
Element and attribute defaults
Where declared
<!DOCTYPE> in the prolog
xsi:schemaLocation hint or parser configuration
Tooling
Simple, universal
Code generation, IDE support
When Each Is Still Used
DTD: legacy formats (older XHTML, DocBook versions), simple documents, and when you need entity definitions.
XSD: SOAP/WSDL web services, financial and government message standards, configuration formats, anything with typed data and namespaces.
Alternatives: RELAX NG is a simpler, more readable schema language; Schematron adds rule-based checks such as “end date after start date”.
Security
DTDs enable XXE and entity-expansion attacks. A common hardening step is to disable DTD processing entirely for untrusted input. That is easier when formats use XSD, because XSD validation does not require a DOCTYPE.
Interview Tip
Lead with the three main differences: XML syntax, data types and namespaces. Then mention that DTDs can declare entities, which is both their remaining use and their security risk. A common mistake is saying a DTD can enforce that a value is a number; it cannot.
23
What are the key components of an XML Schema document?
KnownRevise
An XML Schema (XSD) document is built from a root xs:schema element that sets the target namespace, plus element and attribute declarations, simple and complex type definitions, model groups (sequence, choice, all), facets that restrict values, identity constraints (key, unique, keyref), annotations, and include / import for composing schemas.
Global components (direct children of xs:schema) are named and reusable; global elements can be document roots.
Local components are declared inside a type and used only there.
Named global types (ItemType) make large schemas easier to maintain than deeply nested anonymous types.
Interview Tip
Interviewers often ask about include vs import (same vs different target namespace) and elementFormDefault. A common mistake is forgetting elementFormDefault="qualified", which leaves local elements in no namespace and breaks instance documents that use a default namespace.
24
What data types does XML Schema provide?
KnownRevise
XML Schema data types define what values an element or attribute may contain. XSD has a hierarchy of about 44 built-in types, from xs:string and xs:boolean to numeric, date-time, binary and XML-specific types, plus user-defined simple types made by restricting a built-in type, or by building a list or union of types.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 (XSD 1.1 adds types such as `xs:dateTimeStamp`)
Validation: <quantity>two</quantity> is rejected when the type is xs:positiveInteger.
Data binding: tools map xs:int to int, xs:dateTime to a date-time class and xs:decimal to BigDecimal.
Canonical comparisons: typed values compare correctly in XPath 2.0+ and XQuery (2026-11-04 as a date, not as a string).
Interview Tip
Mention money as xs:decimal with fractionDigits, not xs:double, and the xs:int vs xs:integer range difference. A common mistake is typing everything as xs:string, which throws away most of the value of a schema.
25
How are elements and attributes declared in XML Schema?
KnownRevise
In XML Schema, xs:element declares an element that may appear in a document, with its name, type and how many times it can occur, and xs:attribute declares an attribute an element may carry, with its type, whether it is required, and any default or fixed value. Together they define the vocabulary and its rules, which a validator then enforces.
name and type (a built-in type such as xs:date, or a named simple or complex type).
minOccurs / maxOccurs: cardinality (defaults are 1 and 1; maxOccurs="unbounded" for lists). Only on local elements or references, not global declarations.
default / fixed: value used or required when the element is empty.
nillable="true": lets an instance say <discount xsi:nil="true"/>, meaning explicitly null.
ref: reuse a global element declaration (<xs:element ref="address"/>).
substitutionGroup and abstract: let other elements stand in for this one.
Depends on elementFormDefault / attributeFormDefault
By default, local attributes are unqualified (no namespace prefix), which matches the usual XML style.
Best Practices
Declare few global elements (the real document roots) and use named types for reuse.
Use specific types (xs:positiveInteger, xs:date) instead of xs:string everywhere.
Mark only truly mandatory fields required / minOccurs="1", so the schema can evolve.
Interview Tip
A common mistake is putting minOccurs on a global element declaration, which is not allowed. Also be ready to explain the difference between a missing element, an empty element and xsi:nil="true".
26
What are complex types in XML Schema and how are they used?
KnownRevise
A complex type in XML Schema (xs:complexType) describes an element that has child elements, attributes, or both. It defines the element’s content model: which children appear, in what order and how often, plus its attributes. Complex types can be named and reused, and extended or restricted to build type hierarchies, much like classes.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 and 1.1
Content Models
Content model
Defined with
Example
Element-only
xs:sequence, xs:choice, xs:all
<address> with <street>, <city>
Simple content + attributes
xs:simpleContent + xs:extension
<price currency="USD">19.99</price>
Mixed content
mixed="true"
<p>Text with bold</p>
Empty (attributes only)
No content model
<image src="a.png"/>
Compositors
xs:sequence: children in a fixed order.
xs:choice: exactly one of the alternatives (or several, with maxOccurs).
xs:all: each child at most once, in any order (XSD 1.1 relaxes the limits).
Restriction narrows a base type (fewer occurrences, tighter types).
Instances can choose a derived type with xsi:type="IndianAddressType".
abstract="true" prevents direct use; final and block control derivation.
Why Use Named Complex Types
Reuse: one AddressType for shipping, billing and supplier addresses.
Maintainability: change the type once.
Code generation: JAXB and .NET tools generate one class per named complex type, with inheritance from extensions.
Pitfalls
Deep anonymous nesting makes large schemas hard to read and reuse.
Extension only appends: new elements from an extension come after the base type’s sequence, not in the middle.
Overusing xs:all in XSD 1.0, which has strict limits (maxOccurs of 1 per child).
Interview Tip
Be ready to explain simple vs complex types, the three compositors, and extension vs restriction. A common mistake is trying to add an attribute to a simple type directly; you need a complex type with simple content.
27
What is the difference between simple and complex types in XML Schema?
KnownRevise
A simple type describes a text-only value with no child elements and no attributes, such as an integer, a date or a string matching a pattern. A complex type describes an element that has child elements and/or attributes. Attributes always have simple types; elements can have either.
Simple types are the building blocks for values; complex types assemble them into structures. A good schema defines reusable simple types (PinCode, CurrencyCode, Percentage) and uses them inside complex types, so validation rules live in one place.
Interview Tip
The expected answer is “simple = text only, no attributes; complex = children or attributes”. Mention the simple-content case above, since it is the most common follow-up and the most common mistake.
28
What are facets in XML Schema and how are they used?
KnownRevise
Facets in XML Schema are constraints that restrict the allowed values of a simple type, such as a minimum and maximum, a maximum length, a regular-expression pattern or a fixed list of values. You apply them inside xs:restriction to derive a new, stricter type from a built-in one, for example “a decimal between 0 and 100 with two decimal places”.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 (XSD 1.1 adds `xs:assertion` and `xs:explicitTimezone`)
The Constraining Facets
Facet
Applies to
Meaning
length, minLength, maxLength
Strings, lists, binary
Number of characters (items, bytes)
pattern
Most simple types
Value must match a regular expression
enumeration
Most simple types
Value must be one of a fixed set
minInclusive, maxInclusive
Numbers, dates
Range including the bounds
minExclusive, maxExclusive
Numbers, dates
Range excluding the bounds
totalDigits
Decimals and integers
Maximum number of digits
fractionDigits
Decimals
Maximum digits after the decimal point
whiteSpace
Strings
preserve, replace or collapse
Examples
<!-- Money: up to 10 digits, 2 after the point, not negative -->
<xs:simpleType name="Amount">
<xs:restriction base="xs:decimal">
<xs:totalDigits value="10"/>
<xs:fractionDigits value="2"/>
<xs:minInclusive value="0"/>
</xs:restriction>
</xs:simpleType>
<!-- Fixed set of values -->
<xs:simpleType name="OrderStatus">
<xs:restriction base="xs:string">
<xs:enumeration value="pending"/>
<xs:enumeration value="paid"/>
<xs:enumeration value="shipped"/>
</xs:restriction>
</xs:simpleType>
<!-- Pattern: an Indian PIN code -->
<xs:simpleType name="PinCode">
<xs:restriction base="xs:string">
<xs:pattern value="[1-9][0-9]{5}"/>
</xs:restriction>
</xs:simpleType>
<!-- Length limits -->
<xs:simpleType name="Username">
<xs:restriction base="xs:token">
<xs:minLength value="3"/>
<xs:maxLength value="30"/>
</xs:restriction>
</xs:simpleType>
How Facets Combine
Different facets are combined with AND: the value must satisfy all of them.
Several pattern facets in the same restriction are combined with OR; patterns from successive derivation steps are ANDed.
Several enumeration facets form the allowed set (OR).
A derived type can only tighten facets of its base type, never loosen them.
A fixed="true" attribute on a facet prevents further derived types from changing it.
Pattern Details
XSD patterns are implicitly anchored: the whole value must match, so no ^ or $ is needed.
The regex dialect is XSD’s own: \d and character classes work, but lookaheads and backreferences do not.
Where Facets Help
Data quality at the boundary: reject quantity="-3" or status="sent" before business logic sees it.
Code generation: enumerations become enums in JAXB and .NET.
Documentation: the schema states the real rules of the format.
Limits
Facets check one value at a time. Rules across fields, such as “end date after start date”, need XSD 1.1 assertions or Schematron.
Interview Tip
A common mistake is expecting several patterns to be ANDed, or adding ^...$ anchors. Also mention fractionDigits for money instead of using xs:double.
29
How do namespace declarations work in XML Schema?
KnownRevise
Namespace declarations in an XML Schema tell the schema processor which namespace the schema defines (targetNamespace), how to refer to the XML Schema vocabulary itself (usually xmlns:xs), and how to refer to its own and other schemas’ types (more xmlns prefixes and xs:import). Instance documents then use the same namespace URI so their elements match the schema’s declarations.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 and 1.1, Namespaces in XML 1.0
Prefix for schema keywords (xs:element, xs:string)
targetNamespace="urn:example:orders"
Namespace that the declared elements, attributes and types belong to
xmlns:ord="urn:example:orders"
Prefix to refer to this schema’s own types (ord:StatusType)
xmlns:addr=... + xs:import
Use types from another namespace’s schema
elementFormDefault="qualified"
Local elements also belong to the target namespace
Why targetNamespace Matters
Global elements and types belong to the target namespace. References to them (type="ord:StatusType", ref="ord:order") are QNames, so the prefix must map to that namespace URI. A common error is defining a type in the target namespace and referring to it without a prefix when no default namespace is declared.
The namespace URI must match the schema’s targetNamespace; the prefix (o) can be anything.
xsi:schemaLocation pairs a namespace with a schema file as a hint; validators may use or ignore it.
xsi:noNamespaceSchemaLocation is used for schemas without a target namespace.
elementFormDefault and attributeFormDefault
With elementFormDefault="qualified" (recommended), <o:shipTo> must be in the namespace too.
With the default unqualified, local elements must be in no namespace, so <o:shipTo> would be invalid. This surprises many people.
Attributes are usually left unqualified (attributeFormDefault default).
xs:include vs xs:import
xs:include: brings in a schema with the same target namespace (or none).
xs:import: makes components of a different namespace available.
Interview Tip
The most common bug is a mismatch between the instance’s namespace and the schema’s targetNamespace, or forgetting elementFormDefault="qualified". Explain that prefixes are arbitrary and only the URI counts.
30
What are substitution groups in XML Schema?
KnownRevise
A substitution group in XML Schema lets a set of global elements stand in for a “head” element wherever the head is allowed. If <payment> is the head and <card> and <upi> are members, a content model that references <payment> also accepts <card> or <upi>. It gives element-level polymorphism and lets new alternatives be added without changing the content model.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 and 1.1 (1.1 allows an element to belong to several groups)
How It Works
Declare a global head element, often abstract="true" so it cannot appear itself.
Declare global member elements with substitutionGroup="head".
Each member’s type must be the same as or derived from the head’s type.
Content models reference the head with ref; any member may appear in its place.
New members in other schemas, no change to the content model
New derived types
Benefits
Extensibility: another schema (even in another namespace) can add <wallet substitutionGroup="payment"> without editing order.
Polymorphism: data binding tools such as JAXB map members to subclasses of the head type.
Readable instances: element names say what each item is.
Controls and Pitfalls
block="substitution" on the head prevents substitution in instances; final stops elements from joining the group.
Only global elements can be heads or members.
Members’ types must derive from the head’s type; otherwise the schema is invalid.
Large open groups make it harder to know all valid documents; document the expected members.
Interview Tip
Explain substitution groups as polymorphism at the element-name level and compare them with xsi:type. A common mistake is forgetting that the head must be global and is usually abstract.
31
What is XML parsing and why is it important?
KnownRevise
XML parsing is the process of reading XML text, checking that it is well-formed (and optionally valid against a schema), and turning it into a structure a program can use: an in-memory tree (DOM), a stream of events (SAX), a pull-based cursor (StAX), or objects (data binding). Every application that consumes XML depends on it, and the choice of parser affects memory use, speed and security.
Decodes bytes using the declared or detected encoding.
Normalizes line endings and checks characters are legal.
Tokenizes tags, attributes, text, comments, CDATA and processing instructions.
Checks well-formedness: one root, proper nesting, matching tags, quoted attributes. Any error is fatal.
Resolves entity and character references and namespaces.
Optionally validates against a DTD or XSD and supplies default attribute values.
Delivers the result as a tree, events or objects.
Parsing Models
Model
How it works
Memory
Best for
DOM
Builds the whole tree in memory
High (often several times the file size)
Small to medium documents, random access, editing
SAX (push)
Parser calls your handler for each event
Very low
Huge files, one-pass processing
StAX / pull
Your code asks for the next event
Very low
Streaming with simpler control flow
Data binding
Maps XML directly to typed objects (JAXB)
Medium
Known schemas, business objects
Example in Python
import xml.etree.ElementTree as ET
xml_text = """<orders>
<order id="1"><total>250.00</total></order>
<order id="2"><total>99.50</total></order>
</orders>"""
root = ET.fromstring(xml_text) # tree-based parsing
total = sum(float(o.findtext("total")) for o in root.iter("order"))
print(len(root), "orders, total", total) # 2 orders, total 349.5
Why Parsing Matters
Correctness: a strict parser rejects malformed data instead of silently guessing, which protects downstream systems.
Interoperability: standard parsers mean any platform can read the same document.
Performance: a DOM parser on a 2 GB file can run out of memory; streaming parsers handle it in constant memory.
Validation at the boundary: schema-validating parsers enforce contracts with partners.
Security: parsers are an attack surface.
Security: Configure Parsers Safely
XXE: external entities can read local files or reach internal URLs. Disable DTDs or external entity resolution.
Entity expansion (“billion laughs”): limit or disable entity expansion.
Huge inputs: limit document size and nesting depth.
In Python, use defusedxml for untrusted input; in Java, enable XMLConstants.FEATURE_SECURE_PROCESSING and disallow DOCTYPE declarations.
Interview Tip
Interviewers usually follow up with DOM vs SAX. Answer with the memory trade-off, and mention secure parser configuration; many candidates forget XXE.
32
What is the difference between DOM and SAX parsing?
KnownRevise
DOM parsing reads the whole XML document and builds a complete tree in memory that you can navigate, query and modify in any order. SAX parsing reads the document as a stream and calls your handler for each event (start element, text, end element) as it goes, keeping almost nothing in memory but allowing only one forward pass.
Read full answerHide full answer
Applies toW3C DOM Level 3 and SAX 2.0 (examples: Java JAXP, Python `xml.dom.minidom` / `xml.sax`)
Comparison
Aspect
DOM
SAX
Model
Tree in memory
Event stream (push callbacks)
Memory
Proportional to document size, often several times the file size
Roughly constant
Access
Random, any direction
Sequential, forward only
Modify the document
Yes (add, remove, change nodes)
No; read-only
Speed to first result
After the whole document is parsed
Immediately
Code style
Simple navigation (getElementsByTagName)
Handler state machine
XPath
Easy
Not directly
Best for
Small/medium documents, editing, complex queries
Very large files, one-pass extraction, streaming
DOM Example
from xml.dom import minidom
doc = minidom.parseString("<orders><order id='1'/><order id='2'/></orders>")
orders = doc.getElementsByTagName("order")
print([o.getAttribute("id") for o in orders]) # ['1', '2']
orders[0].setAttribute("status", "paid") # DOM allows editing
print(doc.documentElement.toxml())
SAX Example
import xml.sax
class OrderCounter(xml.sax.ContentHandler):
def __init__(self):
super().__init__()
self.count = 0
def startElement(self, name, attrs): # called for every start tag
if name == "order":
self.count += 1
handler = OrderCounter()
xml.sax.parseString(b"<orders><order id='1'/><order id='2'/></orders>", handler)
print(handler.count) # 2
When to Choose Which
DOM: configuration files, SOAP messages, documents of a few MB that you need to query with XPath, transform or edit.
SAX: multi-GB exports, log files or feeds where you extract or aggregate values in one pass, or when memory is tight.
Pull parsing (StAX) is a third option with SAX’s memory profile but simpler code, because your loop asks for the next event instead of receiving callbacks.
Hybrid: stream the file and build a small tree per record (Python iterparse with elem.clear(), or StAX plus JAXB per element).
Pitfalls
DOM on huge files causes out-of-memory errors.
SAX characters() may be called several times for one text node; buffer text until endElement.
State management in SAX handlers gets complex for deeply nested formats.
Security applies to both: disable external entities and DTDs for untrusted input (for example defusedxml in Python).
Interview Tip
Lead with memory and access pattern, then give a concrete size threshold: if the document comfortably fits in memory and you need random access, use DOM; otherwise stream. The common mistake is forgetting that SAX cannot go back or modify the document.
33
What are the advantages and disadvantages of DOM parsing?
KnownRevise
DOM parsing loads an entire XML document into an in-memory tree of nodes. Its main advantages are random access, easy navigation and querying (including XPath), and the ability to modify and re-serialize the document. Its main disadvantages are high memory use (often several times the file size), slower start-up because the whole document must be parsed first, and poor suitability for very large or streaming data.
Random access: jump to any node, go back to parents or siblings, revisit nodes many times.
Simple programming model: getElementsByTagName, getAttribute and child navigation are easy to read.
Editing: add, remove, reorder and change nodes, then write the document out again.
XPath and XSLT: tree-based queries and transformations work naturally on a DOM.
Standard, language-neutral API: the same concepts in Java, .NET, JavaScript and Python.
Whole-document checks: rules that depend on several parts of the document (cross-references, totals) are easy to verify.
Disadvantages
Memory: every element, attribute and text node is an object. A 100 MB file can need well over 1 GB of heap, depending on the implementation.
Latency: nothing can be processed until parsing finishes.
Not for streams: unbounded feeds or multi-GB exports may never fit in memory.
Verbose API: whitespace text nodes and the generic Node interface make the classic W3C API clumsy (many developers use lighter tree APIs such as ElementTree, dom4j or LINQ to XML).
Thread safety: DOM implementations are generally not thread-safe for concurrent modification.
Summary Table
Factor
DOM
Memory
High, proportional to document size
Navigation
Any direction, repeated
Modification
Supported
Time to first result
After the full parse
Best document size
Small to medium (KBs to tens of MBs)
Example: Read and Modify
from xml.dom import minidom
doc = minidom.parseString("<config><port>8080</port><debug>true</debug></config>")
port = doc.getElementsByTagName("port")[0]
port.firstChild.data = "9090" # change a value
debug = doc.getElementsByTagName("debug")[0]
doc.documentElement.removeChild(debug) # remove a node
print(doc.documentElement.toxml()) # <config><port>9090</port></config>
When to Use DOM
Configuration files, SOAP messages, small API payloads.
Documents you need to edit, transform or query in complex ways.
When the whole document comfortably fits in memory.
Alternatives for Large Documents
SAX or StAX streaming parsers for one-pass processing.
Hybrid: Python iterparse or StAX to stream records, building a small tree per record and discarding it.
Security
DOM parsers process DTDs by default in many languages. Disable external entities and DOCTYPE processing for untrusted input to prevent XXE and entity-expansion attacks.
Interview Tip
Give a size-based rule of thumb and mention both memory and latency. A common mistake is assuming DOM memory equals file size; object overhead makes it several times larger.
34
What is XPath and how is it used with XML?
KnownRevise
XPath (XML Path Language) is a W3C query language for selecting nodes and computing values in an XML document, using path expressions such as /orders/order[@status='paid']/total. It treats the document as a tree and is used by XSLT, XQuery, XML Schema identity constraints, XML Signature and most XML APIs to locate data.
Read full answerHide full answer
Applies toXPath 1.0 (supported almost everywhere) and XPath 3.1 (Saxon and other modern processors)
Path Basics
Expression
Selects
/orders
The root element orders
/orders/order
order children of orders
//order
All order elements anywhere
order/@id
The id attribute of order children
. and ..
Current node and its parent
*
Any element
text()
Text nodes
Predicates
Square brackets filter nodes:
//order[@status='paid']: orders whose status is paid
//order[total > 1000]: orders with total over 1000
//order[1]: the first order child of each parent (XPath indexes start at 1)
Python’s ElementTree supports a limited XPath subset:
import xml.etree.ElementTree as ET
root = ET.fromstring("""<orders>
<order id="1" status="paid"><total>1200</total></order>
<order id="2" status="pending"><total>300</total></order>
<order id="3" status="paid"><total>450</total></order>
</orders>""")
paid = root.findall("./order[@status='paid']")
print([o.get("id") for o in paid]) # ['1', '3']
print(sum(float(o.findtext("total")) for o in paid)) # 1650.0
Full XPath 1.0 is available through lxml in Python, javax.xml.xpath in Java and XPathNavigator / SelectNodes in .NET.
Namespaces
If the document has a default namespace, //order matches nothing. Bind a prefix to the namespace URI in your API and query //o:order. This is the most common XPath bug.
Security and Performance
XPath injection: never build expressions by concatenating user input; use variables or parameters.
// searches the whole tree; on large documents, prefer explicit paths.
Interview Tip
Expect questions on 1-based indexing, // vs /, predicates and namespaces. A common mistake is //order[1], which is the first order of each parent; (//order)[1] is the first in the whole document.
35
What is XSLT and how does it work?
KnownRevise
XSLT (Extensible Stylesheet Language Transformations) is a W3C language for transforming XML documents into other XML, HTML, text or (in 3.0) JSON. An XSLT stylesheet is itself XML: it contains template rules that match parts of the input tree with XPath patterns and describe what output to produce for each match.
1.0: widely available, but limited (no grouping, weak string functions).
2.0: xsl:for-each-group, typed data, regular expressions, user functions.
3.0: streaming for huge documents, maps, JSON input and output, packages.
Common Uses
Converting XML to HTML reports, mapping between partner message formats in integration platforms, generating documentation and publishing formats (DocBook, DITA), and normalizing data before loading it.
Pitfalls
Imperative thinking: variables cannot be reassigned; use recursion or templates.
Namespaces: templates must match namespaced elements with prefixes.
Security: running untrusted stylesheets can call extension functions or read files; disable extensions.
Interview Tip
Explain template matching and apply-templates as the core, and mention the identity transform. A common mistake is writing everything with xsl:for-each, which loses XSLT’s rule-based strength.
36
How do you traverse and modify an XML DOM tree?
KnownRevise
DOM traversal means moving through the in-memory node tree using relationships such as parentNode, childNodes, firstChild and nextSibling, or searching with getElementsByTagName and XPath. DOM manipulation means changing that tree: creating nodes with createElement, adding them with appendChild or insertBefore, removing them with removeChild, and changing attributes and text. The modified tree can then be serialized back to XML.
Read full answerHide full answer
Applies toW3C DOM Level 3 Core (examples in Python `xml.dom.minidom`; same API in Java and JavaScript)
The Node Tree
Every part of the document is a node:
Document node (the whole document)
Element nodes (<order>)
Attribute nodes (accessed through the element)
Text nodes, including whitespace between elements
Comment, CDATA and processing-instruction nodes
Traversal
Property / method
Returns
documentElement
The root element
childNodes
All children, including text nodes
firstChild, lastChild
First/last child node
nextSibling, previousSibling
Neighbours
parentNode
Parent
getElementsByTagName(name)
All descendants with that name
getAttribute(name)
Attribute value
nodeType, nodeName, nodeValue
Information about a node
Manipulation
Method
Effect
createElement, createTextNode
Create new nodes
appendChild, insertBefore
Add nodes
removeChild, replaceChild
Remove or replace nodes
setAttribute, removeAttribute
Change attributes
cloneNode(deep)
Copy a node or subtree
Example
from xml.dom import minidom
doc = minidom.parseString(
"<orders><order id='1'><total>250</total></order>"
"<order id='2'><total>90</total></order></orders>"
)
root = doc.documentElement
# Traversal: walk element children only (skip text nodes)
for node in root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
total = node.getElementsByTagName("total")[0].firstChild.data
print(node.getAttribute("id"), total)
# Manipulation: add a new order
new = doc.createElement("order")
new.setAttribute("id", "3")
total = doc.createElement("total")
total.appendChild(doc.createTextNode("120"))
new.appendChild(total)
root.appendChild(new)
# Remove orders under 100
for order in list(root.getElementsByTagName("order")):
if float(order.getElementsByTagName("total")[0].firstChild.data) < 100:
root.removeChild(order)
print(root.toxml())
Output after the changes: orders 1 and 3 remain.
Pitfalls
Whitespace text nodes: with indented XML, firstChild is often a whitespace text node, not an element. Check nodeType or use element-only properties (firstElementChild in browsers).
Live node lists: in Java and the browser, getElementsByTagName returns a live list that changes as you remove nodes; copy it first (as list(...) does above).
Nodes belong to one document: to move a node between documents, use importNode or adoptNode.
Text access: firstChild.data fails on empty elements; textContent (Java, browsers) is safer.
Memory: everything is in memory, so very large documents need streaming instead.
When to Use XPath Instead
For complex searches, XPath (//order[total < 100]) is shorter and clearer than manual traversal. Use traversal for simple navigation and when editing nearby nodes.
Interview Tip
Mention whitespace text nodes and live node lists. They are the two bugs interviewers expect experienced candidates to know.
37
What is the difference between pull parsing and push parsing in XML?
KnownRevise
In push parsing (SAX), the parser controls the loop: it reads the document and pushes events to your callback methods (startElement, characters, endElement). In pull parsing (StAX, XmlReader), your code controls the loop: it pulls the next event from the parser when it is ready. Both stream the document with low memory; pull parsing is usually easier to write and lets you stop or skip early.
You register a handler; the parser calls it for every event.
Your code must track state across callbacks (“am I inside <total>?”).
You cannot easily pause, skip or stop, except by throwing an exception.
Can be slightly faster, since the parser never waits on your code between events.
Pull Parsing (StAX)
You call next() or iterate; each call returns the next event.
Your parsing logic reads like normal code: loops and method calls per element.
Easy to skip subtrees, stop early once you find what you need, or parse two documents at once.
Simple to delegate: a method can read one element’s contents and return.
Comparison
Aspect
Push (SAX)
Pull (StAX, XmlReader)
Who drives
Parser
Application
Code style
Callbacks, state machine
Loop, ordinary control flow
Memory
Very low
Very low
Stop early
Awkward (exception)
Just stop reading
Skip content
Must ignore events
Can skip elements
Writing XML
No
StAX also has XMLStreamWriter
Typical APIs
Java SAX, Python xml.sax, libxml2 SAX
Java StAX, .NET XmlReader, Python iterparse
Push Example (SAX)
import xml.sax
class Totals(xml.sax.ContentHandler):
def __init__(self):
super().__init__()
self.in_total, self.buf, self.sum = False, [], 0.0
def startElement(self, name, attrs):
self.in_total = name == "total"
self.buf = []
def characters(self, content):
if self.in_total:
self.buf.append(content) # may be called several times per text node
def endElement(self, name):
if name == "total":
self.sum += float("".join(self.buf))
self.in_total = False
h = Totals()
xml.sax.parseString(b"<o><total>10.5</total><total>4.5</total></o>", h)
print(h.sum) # 15.0
Pull Example (iterparse)
import io
import xml.etree.ElementTree as ET
data = io.BytesIO(b"<o><total>10.5</total><total>4.5</total></o>")
total = 0.0
for event, elem in ET.iterparse(data, events=("end",)): # your loop pulls events
if elem.tag == "total":
total += float(elem.text)
elem.clear() # free memory as you go
print(total) # 15.0
When to Use Which
Pull is the default choice for new streaming code: clearer logic and early exit.
Push fits when an existing framework expects SAX handlers, or when pipelines of SAX filters are already in place.
DOM is still simpler when the document is small and you need random access.
Interview Tip
Use the phrase “who owns the loop”. A common mistake is assuming SAX delivers each text node in a single characters() call; buffer the text until endElement.
38
What is XML streaming and what are its benefits?
KnownRevise
XML streaming means processing an XML document incrementally as it is read, one event or small piece at a time, instead of loading the whole document into memory first. Streaming parsers (SAX, StAX, XmlReader, iterparse) and streaming transformations (XSLT 3.0) keep memory use roughly constant, so they can handle documents of many gigabytes or never-ending feeds.
The parser reads bytes from a file, socket or HTTP response.
It emits events (start element, text, end element) as soon as each construct is complete.
Your code handles each event or each small subtree (for example one <record>), then discards it.
Memory holds only the current path and small buffers, not the whole document.
Benefits
Constant memory: a 10 GB product feed can be processed on a machine with 512 MB of RAM.
Low latency: the first records are processed while the rest is still downloading.
Handles unbounded data: long-running feeds and log streams that have no practical end.
Throughput: no time spent building a large object tree; less garbage-collection pressure.
Pipelines: streams can be chained (parse, filter, transform, write) without intermediate files.
Early exit: stop as soon as you find what you need (with pull parsers).
Comparison With Tree-Based Processing
Aspect
Streaming
DOM / tree
Memory
Constant
Proportional to document size
Random access
No (forward only)
Yes
Edit in place
No (write a new stream)
Yes
Cross-document checks
Hard
Easy
Large files
Ideal
Risky
Example: Stream Records From a Large Export
import io
import xml.etree.ElementTree as ET
# Imagine this is a multi-GB file; only one <product> is in memory at a time
feed = io.BytesIO(b"""<catalog>
<product sku="A1"><price>199</price></product>
<product sku="B2"><price>1450</price></product>
<product sku="C3"><price>820</price></product>
</catalog>""")
expensive = []
for event, elem in ET.iterparse(feed, events=("end",)):
if elem.tag == "product":
if float(elem.findtext("price")) > 500:
expensive.append(elem.get("sku"))
elem.clear() # release the processed subtree
print(expensive) # ['B2', 'C3']
Common Use Cases
Importing large catalogues, sitemaps or government data dumps.
Processing Wikipedia or OpenStreetMap XML exports.
Message-by-message processing in integration pipelines.
Generating large XML output with a streaming writer (StAX XMLStreamWriter, XmlWriter) instead of building a DOM.
Limitations
Forward-only: you cannot look ahead or go back without buffering yourself.
More complex logic for rules that depend on distant parts of the document (for example, totals at the end that must match all records).
Validation: streaming XSD validation is possible, but rules that need the whole document need extra work.
Interview Tip
Mention the hybrid pattern shown above: stream the file, build a small tree per record, then clear it. A common mistake with iterparse is forgetting clear(), which slowly builds the whole tree in memory anyway.
39
What are SAX events and how are they handled?
KnownRevise
SAX events are the notifications a SAX parser sends as it reads an XML document from start to finish: startDocument, startElement (with the name and attributes), characters (text), endElement, endDocument, plus events for namespaces, processing instructions and ignorable whitespace. You handle them by implementing a content handler whose methods the parser calls in document order, and you keep whatever state you need between calls.
Whitespace in element-only content (with a validating DTD)
processingInstruction(target, data)
A processing instruction is read
endElement(name)
An end tag is read
endDocument()
Parsing ends
Errors go to a separate error handler (warning, error, fatalError). In Java, namespace-aware callbacks are startElement(uri, localName, qName, attributes); in Python, use startElementNS with the namespaces feature enabled.
Event Sequence Example
For <order id="7"><total>250</total></order>, the parser fires:
startDocument
startElement("order", {id: "7"})
startElement("total", {})
characters("250")
endElement("total")
endElement("order")
endDocument
Handling Events
import xml.sax
class OrderHandler(xml.sax.ContentHandler):
def __init__(self):
super().__init__()
self.path = [] # current element path
self.text = [] # buffer for character chunks
self.orders = []
def startElement(self, name, attrs):
self.path.append(name)
self.text = []
if name == "order":
self.orders.append({"id": attrs.get("id")})
def characters(self, content):
self.text.append(content) # may arrive in pieces
def endElement(self, name):
if name == "total" and self.path[-2:] == ["order", "total"]:
self.orders[-1]["total"] = float("".join(self.text).strip())
self.path.pop()
h = OrderHandler()
xml.sax.parseString(b"<orders><order id='7'><total>250</total></order>"
b"<order id='8'><total>99.5</total></order></orders>", h)
print(h.orders) # [{'id': '7', 'total': 250.0}, {'id': '8', 'total': 99.5}]
Handling Patterns
Track the path with a stack, so you know where you are in the tree.
Buffer text from characters() and use it at endElement.
Build small objects per record and pass them on (save to a database, emit to a queue), then discard them.
Copy attributes you need during startElement; the Attributes object may be reused by the parser afterwards.
Pitfalls
Split text: characters() can be called several times for one text node, especially across buffer boundaries or entities.
Deep state machines: complex formats make handlers hard to maintain; pull parsing (StAX) is often clearer.
Security: SAX parsers process DTDs too; disable external entities (for example parser.setFeature(xml.sax.handler.feature_external_ges, False) in Python, or use defusedxml.sax).
Interview Tip
Walk through the event sequence for a tiny document and mention text chunking. Interviewers often ask how to know which element a piece of text belongs to; the answer is a path stack.
40
What is StAX and how is it used for XML processing?
KnownRevise
StAX (Streaming API for XML, JSR 173) is a Java API for pull-based XML parsing and writing. Your code asks the parser for the next event with next() or nextEvent(), so you control the loop while keeping memory use low. It also includes XMLStreamWriter for writing large XML documents in a streaming way. It is part of the JDK in the javax.xml.stream package.
Read full answerHide full answer
Applies toJava SE 6+ (`javax.xml.stream`), including Java 21
Two API Styles
API
Classes
Style
Cursor API
XMLStreamReader, XMLStreamWriter
Fast, low-level: the reader is the current event
Iterator (event) API
XMLEventReader, XMLEventWriter
Event objects you can store, peek at and pass around
The cursor API is usually faster and allocates less; the event API is more flexible.
Typical Use: Read Large Files Record by Record
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
public class OrderTotals {
public static void main(String[] args) throws Exception {
XMLInputFactory factory = XMLInputFactory.newFactory();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // block XXE
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
double sum = 0;
try (InputStream in = new FileInputStream("orders.xml")) {
XMLStreamReader reader = factory.createXMLStreamReader(in);
try {
while (reader.hasNext()) {
if (reader.next() == XMLStreamConstants.START_ELEMENT
&& reader.getLocalName().equals("total")) {
sum += Double.parseDouble(reader.getElementText()); // reads text, moves to END_ELEMENT
}
}
} finally {
reader.close(); // XMLStreamReader is not AutoCloseable
}
}
System.out.println("Total: " + sum);
}
}
Writing XML With StAX
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
StringWriter out = new StringWriter();
XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(out);
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("order");
w.writeAttribute("id", "42");
w.writeStartElement("total");
w.writeCharacters("250.00"); // escaping is handled for you
w.writeEndElement();
w.writeEndElement();
w.writeEndDocument();
w.close();
System.out.println(out);
Why Use StAX
Low memory: suitable for files of many gigabytes.
Simple control flow: ordinary loops instead of SAX callbacks.
Stop or skip early: stop reading once you find what you need.
Streaming output: generate huge documents without building a DOM.
Combine with JAXB: move the reader to each <order> element and unmarshal just that element into an object.
StAX vs SAX vs DOM
DOM
SAX
StAX
Model
Tree
Push events
Pull events
Memory
High
Low
Low
Control
Random access
Parser drives
Application drives
Can write XML
Yes (serialize)
No
Yes
Pitfalls
getElementText() throws if the element contains child elements; use it only for text-only elements.
Forgetting to close readers and writers (they do not implement AutoCloseable).
Insecure defaults: disable DTD support and external entities for untrusted input.
Interview Tip
Explain the cursor vs event APIs and the pull model. A strong answer mentions combining StAX with JAXB for “stream the file, bind each record” processing.
41
What is the XML DOM and what is it used for?
KnownRevise
The XML DOM (Document Object Model) is a W3C standard, language-neutral API that represents an XML document as a tree of objects (nodes) in memory. Programs use it to read, navigate, search, create, modify and delete parts of a document, then serialize the result back to XML.
Reading configuration and messages with random access to any part.
Editing documents: updating values, adding or removing elements, then saving.
Building XML programmatically with createElement and appendChild, which handles escaping.
Running XPath and XSLT over a tree.
Validating and signing: XML Signature implementations typically work on a DOM.
Web pages: browsers expose HTML and XML documents through the same DOM model to JavaScript.
Example
from xml.dom import minidom
doc = minidom.parseString('<library><book id="b1"><title>XML Basics</title></book></library>')
book = doc.getElementsByTagName("book")[0]
print(book.getAttribute("id")) # b1
print(book.getElementsByTagName("title")[0].firstChild.data) # XML Basics
# Create and add a new book
new_book = doc.createElement("book")
new_book.setAttribute("id", "b2")
title = doc.createElement("title")
title.appendChild(doc.createTextNode("Schemas & Namespaces")) # & is escaped on output
new_book.appendChild(title)
doc.documentElement.appendChild(new_book)
print(doc.documentElement.toxml())
Strengths and Weaknesses
Strength
Weakness
Random access and editing
Whole document in memory
Standard API across languages
Verbose, generic node API
Works with XPath, XSLT, XML Signature
Slow start for big files
Lighter Tree APIs
Many developers use friendlier tree models built on the same idea: Python’s ElementTree and lxml, Java’s dom4j, JDOM or XOM, and .NET’s LINQ to XML (XDocument).
Security
Configure DOM parsers to disable DTDs and external entities for untrusted input (in Java, factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)), to prevent XXE.
Interview Tip
Define the DOM as an API and object model, not a file format. A common follow-up is DOM vs SAX; answer with memory use and access pattern.
42
What is SAX in XML and when should you use it?
KnownRevise
SAX (Simple API for XML) is an event-driven, push-based XML parsing API: the parser reads the document sequentially and calls methods on your handler (startElement, characters, endElement, …) for each construct it encounters, without building a tree. Use it when documents are too large for memory, when you need one fast pass to extract or aggregate data, or when processing must start before the whole document arrives.
Create a parser and register a ContentHandler (and optionally an ErrorHandler).
The parser streams through the input.
For each start tag, chunk of text and end tag, it calls your handler.
Your handler keeps only the state it needs, such as the current path or a running total.
When the document ends, the parser calls endDocument.
Example: Count Products by Category
import xml.sax
from collections import Counter
class CategoryCounter(xml.sax.ContentHandler):
def __init__(self):
super().__init__()
self.counts = Counter()
def startElement(self, name, attrs):
if name == "product":
self.counts[attrs.get("category", "unknown")] += 1
data = b"""<catalog>
<product category="books"/><product category="toys"/>
<product category="books"/>
</catalog>"""
handler = CategoryCounter()
xml.sax.parseString(data, handler)
print(dict(handler.counts)) # {'books': 2, 'toys': 1}
For untrusted input in Python, use defusedxml.sax instead of xml.sax.
When to Use SAX
Large files: GB-sized exports, data dumps, log archives.
One-pass tasks: counting, summing, filtering, converting records to database rows.
Low-memory environments: small containers, embedded systems.
Streaming input: start processing while data is still downloading.
SAX filter pipelines: chained XMLFilters that transform events on the fly.
When Not to Use SAX
You need random access or must look at earlier parts again.
You need to modify the document.
The logic needs XPath or depends on many parts of the document.
The document is small; DOM or ElementTree code is simpler.
You want streaming with simpler code: StAX / pull parsing is often clearer.
Advantages and Disadvantages
Advantages
Disadvantages
Constant, low memory
Forward-only, read-only
Fast; processing starts immediately
Handler state machines get complex
Works on endless or huge input
No XPath
Mature and available everywhere
Text may arrive in several characters() calls
Pitfalls
Chunked text: always buffer characters() output and use it at endElement.
Namespace handling: enable namespace support to get URIs and local names.
Attributes object reuse: copy values you need during startElement.
Security: disable external entities and DTDs for untrusted input.
Interview Tip
A good answer explains when SAX is the right tool, with a size or memory argument, and mentions pull parsing as the modern streaming alternative. A common mistake is choosing SAX for small documents where the extra code complexity is not justified.
43
What is JAXP in Java and what are its key components?
KnownRevise
JAXP (Java API for XML Processing) is the standard Java API for parsing, validating, transforming and querying XML, independent of any particular implementation. It defines factory classes for DOM (DocumentBuilderFactory), SAX (SAXParserFactory), StAX (XMLInputFactory / XMLOutputFactory), XSLT (TransformerFactory), XPath (XPathFactory) and schema validation (SchemaFactory). The JDK ships with built-in implementations, which can be replaced by others such as Xerces or Saxon.
JAXP uses the factory pattern: DocumentBuilderFactory.newInstance() finds an implementation through a system property, the service-loader mechanism, or falls back to the JDK default. Application code stays the same if you switch to another implementation.
Example: Secure DOM Parse, XPath Query and Validation
The built-in XSLT processor supports XSLT 1.0 and XPath 1.0 only; for XSLT 3.0 and XPath 3.1, use Saxon through the same TransformerFactory interface.
Factories are not guaranteed thread-safe; builders, parsers and transformers are not thread-safe either. Create them per thread or pool them. Compiled Templates and Schema objects are thread-safe and reusable.
Interview Tip
List the six areas and their factories, then stress secure configuration: JAXP defaults historically allowed DTDs and external entities, which leads to XXE. A common mistake is calling DocumentBuilderFactory.newInstance() without disabling DOCTYPE declarations on untrusted input.
44
What is JAXB and what are its benefits?
KnownRevise
JAXB (Jakarta XML Binding, formerly Java Architecture for XML Binding) is a Java standard for mapping XML to Java objects and back. Unmarshalling turns an XML document into objects; marshalling writes objects as XML. Mappings come from annotations such as @XmlRootElement and @XmlElement, or classes can be generated from an XSD with the xjc tool.
Read full answerHide full answer
Applies toJakarta XML Binding 4.0 (`jakarta.xml.bind`, reference implementation `org.glassfish.jaxb:jaxb-runtime`). JAXB was removed from the JDK in Java 11, so add it as a dependency.
How It Works
Annotate classes, or generate them from a schema with xjc orders.xsd.
Create a JAXBContext for the root classes (expensive, so create it once and reuse it; it is thread-safe).
Create a Marshaller or Unmarshaller per use (cheap, not thread-safe).
Convert between XML and objects.
Example
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
@XmlRootElement(name = "order")
@XmlAccessorType(XmlAccessType.FIELD)
class Order {
@XmlAttribute
String id;
@XmlElement
String customer;
@XmlElement
BigDecimal total; // maps to xs:decimal; exact for money
}
public class JaxbDemo {
public static void main(String[] args) throws Exception {
JAXBContext ctx = JAXBContext.newInstance(Order.class); // reuse this
String xml = "<order id=\"42\"><customer>Asha</customer><total>1250.50</total></order>";
Order order = (Order) ctx.createUnmarshaller().unmarshal(new StringReader(xml));
System.out.println(order.customer + " " + order.total); // Asha 1250.50
order.total = order.total.add(new BigDecimal("100"));
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter out = new StringWriter();
m.marshal(order, out);
System.out.println(out);
}
}
Common Annotations
Annotation
Purpose
@XmlRootElement
Class can be a document root
@XmlElement
Field or property becomes a child element
@XmlAttribute
Field becomes an attribute
@XmlElementWrapper
Wraps a collection in a container element
@XmlTransient
Exclude a field
@XmlJavaTypeAdapter
Custom conversion (for example LocalDate)
@XmlType(propOrder = ...)
Control element order
@XmlAccessorType
Bind fields or properties
Benefits
Less code: no manual DOM or SAX handling for typical documents.
Type safety: work with Order and BigDecimal, not strings and nodes.
Schema-first development: generate classes from a partner’s XSD so the code matches the contract.
Validation: attach a Schema to the unmarshaller (setSchema) to reject invalid input.
Ecosystem: used by Jakarta SOAP (JAX-WS), and supported by JAX-RS for XML payloads.
Limitations and Pitfalls
Whole objects in memory: for huge files, combine with StAX and unmarshal one record at a time.
Not in the JDK since Java 11: add jakarta.xml.bind-api and jaxb-runtime. The javax.xml.bind package was renamed to jakarta.xml.bind in Jakarta EE 9.
Mixed content and complex schemas map awkwardly.
Security: unmarshal from a securely configured XMLStreamReader or SAXSource (DTDs disabled) when input is untrusted.
Interview Tip
Mention marshalling vs unmarshalling, xjc for schema-first design, and the javax to jakarta change. A common mistake is creating a new JAXBContext for every request, which is slow.
45
What is XQuery and how does it differ from XPath?
KnownRevise
XQuery is a W3C query and transformation language for XML, often described as “SQL for XML”. It uses XPath expressions to select data and adds FLWOR expressions (for, let, where, order by, return), joins, grouping, functions, modules and construction of new XML. XPath is the smaller expression language that only selects nodes or computes values within a document. Every XPath expression is valid XQuery, but not the other way round.
Read full answerHide full answer
Applies toXQuery 3.1 and XPath 3.1 (W3C Recommendations, 2017); XPath 1.0 is still the most widely supported version
What XQuery Adds to XPath
FLWOR expressions for iteration, filtering, sorting and grouping.
Constructing new XML (and JSON in 3.1) in the result.
Joins across documents or collections.
User-defined functions and modules.
Querying collections, for example all documents in an XML database.
Updates through the separate XQuery Update Facility.
XQuery can build a new report, grouped and sorted:
<report>{
for $o in doc("orders.xml")//order
let $c := $o/@customer
group by $c
order by sum($o/total) descending
return <customer name="{$c}" orders="{count($o)}" total="{sum($o/total)}"/>
}</report>
Nodes, strings, numbers, booleans (sequences in 2.0+)
Any XML (or JSON) you construct
Iteration
Implicit in paths; for in 2.0+
Full FLWOR
Sorting and grouping
No (sorting via sort() in 3.1)
order by, group by
Functions
Built-in library
User-defined functions and modules
Typical host
XSLT, XML Schema, DOM APIs, Selenium
XML databases (BaseX, eXist-db, MarkLogic), Saxon
Size
Small expression language
Full programming language
XQuery vs XSLT
Both can transform XML. XSLT is rule-based (templates matching nodes), good for document-to-document transformations with many small changes. XQuery is query-oriented, good for selecting, joining and aggregating data, especially over collections in XML databases.
Where XQuery Is Used
XML databases and content repositories (publishing, legal and scientific documents).
SQL Server and Oracle XML columns (subsets of XQuery).
Data integration with Saxon.
Interview Tip
The key line: XPath locates data; XQuery queries and builds new results using XPath inside FLWOR. A common mistake is saying XQuery replaces XPath; it is a superset built on top of it.
46
How are XML namespaces used across XML technologies?
KnownRevise
XML namespaces identify vocabularies by URI so that element and attribute names from different specifications can be combined without clashing. Every major XML technology relies on them: XSD uses them to define and validate vocabularies, XSLT and XPath use prefixes to match namespaced nodes, SOAP separates its envelope from application payloads, XML Signature and Encryption add their own elements inside other documents, and formats such as SVG, XHTML and Office Open XML are defined by their namespaces.
Read full answerHide full answer
Applies toNamespaces in XML 1.0 (Third Edition) and the W3C specifications that build on it
A name’s identity is (namespace URI, local name). The prefix is only a local shorthand, and the default namespace (xmlns="...") applies to unprefixed elements, not attributes.
Namespaces in Each Technology
Technology
How namespaces are used
Key URI
XML Schema
targetNamespace defines the vocabulary; xs:import combines vocabularies
http://www.w3.org/2001/XMLSchema
Schema instances
xsi:schemaLocation, xsi:type, xsi:nil
http://www.w3.org/2001/XMLSchema-instance
XSLT
Instructions are in the XSLT namespace; templates match source namespaces via prefixes
http://www.w3.org/1999/XSL/Transform
XPath / XQuery
Prefixes bound in the host API select namespaced nodes
(host-defined bindings)
SOAP 1.2
Envelope, header and body elements separate from payload
The stylesheet’s prefix can differ from the document’s; only the URI must match.
Example: Python With Namespaces
import xml.etree.ElementTree as ET
doc = ET.fromstring('<invoice xmlns="urn:example:invoice"><number>INV-7</number></invoice>')
print(doc.find("number")) # None: wrong name
print(doc.find("i:number", {"i": "urn:example:invoice"}).text) # INV-7
print(doc.tag) # {urn:example:invoice}invoice
Design Guidance
One namespace per vocabulary, and version it deliberately (urn:example:invoice:v2 signals a breaking change).
Use stable, owned URIs (a domain you control or a URN).
Declare namespaces on the root element to keep documents readable.
Pitfalls
Default namespace surprises: queries without a prefix find nothing.
Prefix comparisons in code instead of URI comparisons.
Canonicalization and signatures: namespace declarations affect the signed bytes; exclusive canonicalization (exc-c14n) handles this when signed fragments move between documents.
Interview Tip
Show that you know the URI is the identity and give two or three technology examples (XSD targetNamespace, XSLT prefix matching, SOAP envelopes). The most common real-world bug is the default namespace in XPath.
47
What is XML Signature and what role does it play in XML security?
KnownRevise
XML Signature (XMLDSig) is a W3C standard for digitally signing XML documents or parts of them. It provides integrity (the signed data has not changed), authentication of the signer, and, with certificate-based keys, non-repudiation. The signature is itself XML (<ds:Signature>) and can be enveloped (inside the signed document), enveloping (wrapping the data) or detached (separate from it).
Read full answerHide full answer
Applies toXML Signature Syntax and Processing Version 1.1 (W3C Recommendation, 2013)
What It Protects
Integrity: any change to the signed content breaks the signature.
Authenticity: only the holder of the private key could have produced it.
Non-repudiation: with a certificate from a trusted authority, the signer cannot easily deny signing.
It does not provide confidentiality; for that, use XML Encryption or TLS.
Points to the signed data (URI), lists transforms and holds its digest
Transforms
Steps applied before hashing (remove the signature itself, canonicalize)
SignedInfo
The part that is actually signed: references plus algorithms
SignatureValue
Signature over the canonicalized SignedInfo
KeyInfo
Optional hint about the key (certificate, key name)
Signature Types
Type
Where the signature is
Example use
Enveloped
Inside the signed document
SAML assertions, e-invoices
Enveloping
Wraps the signed data inside ds:Object
Self-contained signed packages
Detached
Separate; references data by URI
Signing a file or a sibling element
Where It Is Used
SAML 2.0 single sign-on: identity providers sign assertions.
WS-Security for SOAP messages.
E-invoicing and e-government documents, and XAdES advanced electronic signatures.
Signed configuration and licence files.
Security Considerations
Use strong algorithms: RSA-SHA256 or ECDSA-SHA256 and SHA-256 digests; do not accept SHA-1 or MD5.
Signature wrapping attacks: an attacker moves the signed element and inserts a forged one where the application reads data. Verify that the element your code uses is the element that was signed (check the reference ID resolves to that exact node), and reject duplicate IDs.
Trust the key properly: validate the certificate chain against your trust store; never trust a key just because it is embedded in KeyInfo.
Restrict transforms: allow only the expected ones (enveloped-signature, exclusive canonicalization); disallow XSLT transforms and external URIs.
Use a maintained library (Apache Santuario, the Java XML Digital Signature API, .NET SignedXml, xmlsec); never write your own.
Interview Tip
Explain what is hashed (references), what is signed (SignedInfo) and why canonicalization exists. Mentioning signature wrapping, which caused real SAML vulnerabilities, is what interviewers look for in a senior answer.
48
What is XML Encryption and what is it for?
KnownRevise
XML Encryption is a W3C standard for encrypting XML content: a whole document, a single element, only an element’s content, or arbitrary data, so that only intended recipients can read it. The encrypted part is replaced by an <xenc:EncryptedData> element containing the ciphertext and information about the algorithm and key, while the rest of the document stays readable.
Read full answerHide full answer
Applies toXML Encryption Syntax and Processing Version 1.1 (W3C Recommendation, 2013)
Purpose
Confidentiality of selected parts: encrypt only the card number or medical details, leaving routing information readable for intermediaries.
End-to-end protection: data stays encrypted through queues, gateways and storage, beyond what TLS (which protects only one hop) covers.
Different recipients for different parts: each section can be encrypted for a different key.
How It Works
Generate a random content-encryption key (for example an AES-256 key).
Encrypt the selected XML with that key, using AES-GCM.
Encrypt (wrap) the content key for each recipient with their public key (RSA-OAEP) or a shared key-wrap key, stored in <xenc:EncryptedKey>.
Replace the original element or content with <xenc:EncryptedData>.
The recipient unwraps the content key with their private key and decrypts the data.
SAML encrypted assertions (EncryptedAssertion), so only the service provider can read user attributes.
WS-Security for SOAP message parts.
Healthcare, finance and government messages that pass through several intermediaries.
Security Considerations
Use AES-GCM: XML Encryption 1.0’s AES-CBC mode is vulnerable to padding-oracle attacks (shown in 2011 research); XML Encryption 1.1 adds GCM.
Use RSA-OAEP for key transport, not RSA PKCS#1 v1.5.
Encryption is not integrity: combine with XML Signature (or rely on GCM’s authentication) and decide the order (commonly sign, then encrypt).
Avoid error oracles: return the same generic error for any decryption failure.
Key management is the hard part: protect private keys in an HSM or key vault and rotate them.
Use maintained libraries (Apache Santuario, xmlsec); never implement the algorithms yourself.
Interview Tip
Contrast with TLS (transport, hop by hop) and explain the hybrid scheme (AES content key wrapped with RSA-OAEP). Mentioning the CBC padding-oracle issue and the move to GCM in 1.1 shows real depth.
49
What is XML canonicalization and why is it needed?
KnownRevise
XML canonicalization (C14N) converts an XML document into a standard byte-for-byte form, so that documents that are logically the same (differing only in attribute order, quote style, empty-element syntax, line endings or redundant namespace declarations) produce identical bytes. Its main use is XML Signature: a digest is computed over bytes, so sender and receiver must serialize the XML in exactly the same way.
Read full answerHide full answer
Applies toCanonical XML 1.0 and 1.1, Exclusive XML Canonicalization 1.0 (W3C Recommendations)
The Problem
These two documents mean the same thing but have different bytes, so their SHA-256 hashes differ:
Any parser, proxy or library that re-serializes a document can introduce such differences and break a signature, even though nothing meaningful changed.
What Canonicalization Does
Encodes the document in UTF-8.
Normalizes line breaks to #xA.
Writes attribute values with double quotes and normalized escaping.
Sorts attributes (namespace declarations first, then attributes by namespace URI and local name).
Writes empty elements as start and end tag pairs (<note></note>).
Expands entity and character references and replaces CDATA sections with their escaped text.
Removes the XML declaration and the DOCTYPE, and removes superfluous namespace declarations.
Keeps whitespace inside the root element exactly as it is (canonicalization does not pretty-print).
Comments are kept or removed depending on the variant (“with comments” or the default without).
Variants
Variant
Algorithm URI (short)
Key behaviour
Canonical XML 1.0
xml-c14n-20010315
Inherits namespace declarations from ancestors into a signed subset
Canonical XML 1.1
xml-c14n11
Fixes handling of xml:id and xml:base
Exclusive C14N
xml-exc-c14n#
Only includes namespaces the signed fragment actually uses
Exclusive canonicalization is the usual choice for SAML and SOAP, because signed fragments are often moved into a different parent document with different namespace declarations; inclusive C14N would then give different bytes.
Example in Python
Python 3.8+ includes C14N 2.0 support:
import xml.etree.ElementTree as ET
a = "<order status='paid' id=\"42\"><note/></order>"
b = '<order id="42" status="paid"><note></note></order>'
print(ET.canonicalize(a)) # <order id="42" status="paid"><note></note></order>
print(ET.canonicalize(a) == ET.canonicalize(b)) # True
Where It Is Used
XML Signature: canonicalizing SignedInfo and referenced data before hashing.
Comparing documents for logical equality in tests.
Deduplication and caching keyed on document content.
Limits
Canonicalization does not remove insignificant whitespace between elements: a pretty-printed and a compact document still differ.
It does not sort elements, because element order is significant in XML.
It is relatively expensive on large documents.
Interview Tip
Connect C14N directly to signatures, and explain why exclusive canonicalization is preferred for signed fragments. A common mistake is assuming canonicalization ignores all formatting differences; indentation changes still break signatures.
50
What are XML Catalogs and what benefits do they provide?
KnownRevise
XML Catalogs are an OASIS standard that maps public identifiers, system identifiers and URIs (for DTDs, schemas, stylesheets and entities) to local copies. When a parser or processor needs a resource such as http://www.w3.org/2001/xml.xsd, the catalog resolver redirects it to a local file instead of fetching it over the network.
Read full answerHide full answer
Applies toOASIS XML Catalogs 1.1 (2005); supported by Java (`javax.xml.catalog`, since Java 9), libxml2 (`xmllint --catalogs`), Saxon and Apache resolvers
The Problem They Solve
Documents and schemas refer to external resources by identifiers:
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
Without a catalog, every parse may download these files. That is slow, fails offline, depends on a remote server staying up (the W3C rate-limits heavy automated DTD downloads), and is a security risk.
Other URI references (schemas, stylesheets, namespaces)
rewriteSystem / rewriteURI
A whole URL prefix to a local directory
nextCatalog
Chains to another catalog file
Benefits
Performance: no network round trips (often hundreds of milliseconds each) on every parse.
Reliability: works offline and in locked-down production networks.
Reproducibility: everyone uses the same, versioned local copy of each schema.
Security: prevents unexpected outbound requests, which reduces SSRF and XXE-style risks when combined with blocking unknown resources.
Decoupling: documents keep their standard public identifiers while each environment decides where files physically live.
Version control: schemas can be stored in the repository next to the code.
Using a Catalog in Java
import java.net.URI;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.RESOLVE, "strict") // fail if a resource is not in the catalog
.build();
CatalogResolver resolver = CatalogManager.catalogResolver(
features, URI.create("file:///app/xml/catalog.xml"));
// Use resolver as the EntityResolver / LSResourceResolver / URIResolver of parsers and transformers
With RESOLVE=strict, any resource missing from the catalog causes an error instead of a network fetch.
Pitfalls
Catalog entries must match identifiers exactly (or by the rewrite prefix).
Each tool needs to be configured to use the catalog.
Keep local copies in sync when a standard publishes a new version.
Interview Tip
Present catalogs as “DNS for XML resources”. Interviewers value the security and reliability angle: production systems should never download schemas or DTDs at parse time.
51
What are best practices for designing XML Schemas?
KnownRevise
Good XML Schema design produces contracts that are precise enough to catch bad data, flexible enough to evolve, and easy for partners and tools to use. The main practices are: use a target namespace with qualified elements, prefer named, reusable types, apply specific data types and facets, keep required fields minimal, plan versioning and extension points from the start, and document the schema inside it.
Read full answerHide full answer
Applies toW3C XML Schema 1.0 (with notes on 1.1)
Structure and Naming
Always use a targetNamespace you control (urn:acme:orders:v1 or https://schemas.acme.com/orders/v1).
Set elementFormDefault="qualified"; leave attributes unqualified.
Pick one naming convention: for example UpperCamelCase types (OrderType) and lowerCamelCase elements (orderDate).
Use named global types and few global elements (the Venetian Blind pattern), so types are reusable and only real root elements can start a document.
Split large schemas into modules (xs:include for the same namespace, xs:import for shared libraries such as common address types).
Data Quality
Use specific types: xs:date, xs:positiveInteger, xs:boolean, not xs:string everywhere.
Use xs:decimal with fractionDigits for money, never xs:float or xs:double.
Restrict values with facets: enumerations for statuses, patterns for codes, length limits for free text.
Use xs:key / xs:keyref for references inside a document.
Flexibility and Evolution
Make elements optional unless truly required: adding an optional element later is backward compatible; adding a required one is not.
Add extension points: <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> at the end of key types lets partners add data without breaking validation. Use them carefully; in XSD 1.0, wildcards must not create ambiguous content models.
Plan versioning: a version attribute on the root for minor, compatible changes; a new namespace for breaking changes.
Avoid xs:all and deep xs:choice structures that become hard to extend.
Usability
Document every type and element with xs:annotation / xs:documentation.
Provide sample instance documents and validate them in CI.
Keep element-vs-attribute rules consistent: data in elements, metadata (ids, units, codes) in attributes.
Consider code generation: JAXB and .NET tools work best with named types and avoid odd constructs such as complex xs:choice and xs:group nesting.
Everything as xs:string, so the schema validates almost nothing.
Everything required, so every new field is a breaking change.
Deeply nested anonymous types (Russian Doll) in large schemas, preventing reuse.
No namespace, making it impossible to combine with other vocabularies.
Business rules across fields left undocumented (use XSD 1.1 assertions or Schematron if needed).
Interview Tip
Structure your answer as correctness, reuse and evolution. Interviewers often ask “how would you add a field without breaking existing clients?”; the answer is an optional element, or an extension point, plus a versioning policy.
52
What is XML modularity and what are its benefits?
KnownRevise
XML modularity means splitting XML vocabularies, schemas and documents into separate, reusable modules that are combined when needed: schemas through xs:include, xs:import and xs:redefine / xs:override, documents through XInclude or entities, and stylesheets through xsl:include / xsl:import. Each module covers one concern, such as addresses, payments or common types, and can be maintained and reused independently.
Read full answerHide full answer
Applies toW3C XML Schema 1.0/1.1, XInclude 1.0, XSLT 1.0–3.0, Namespaces in XML 1.0
The processor replaces each xi:include with the referenced document’s content (XInclude processing must be enabled in the parser).
Benefits
Reuse: one AddressType used by orders, invoices and customer schemas.
Consistency: change a shared type once; every vocabulary that imports it follows.
Maintainability: smaller files with clear ownership, easier code review and diffs.
Team scalability: different teams own different modules.
Selective use: partners import only the modules they need.
Independent versioning of shared libraries and domain schemas.
Trade-offs and Pitfalls
Dependency management: modules depend on each other; version them deliberately and avoid cycles.
Breaking changes spread: changing a shared type affects every importing schema; keep shared modules stable.
Resolution: tools must find all modules; use relative paths or XML Catalogs.
xs:redefine is fragile and poorly supported; prefer extension or xs:override in XSD 1.1.
Security: XInclude and external entities can read local files; enable them only for trusted documents.
Interview Tip
Distinguish xs:include (same namespace) from xs:import (different namespace), the most common follow-up question. Mention that modularity is to schemas what libraries are to code.
53
How do you version XML formats and schemas?
KnownRevise
XML versioning manages changes to an XML format over time so that producers and consumers using different versions can keep working together. It is achieved with a clear compatibility policy (which changes are allowed without a new version), a visible version identifier (a version attribute, the namespace URI, or the schema file name), design for extension (optional elements, wildcards), and running old and new versions side by side during migrations.
Read full answerHide full answer
Applies toW3C XML Schema 1.0/1.1 practices; general contract-versioning principles
Compatible vs Breaking Changes
Change
Backward compatible?
Add an optional element or attribute
Yes (if consumers ignore unknown content or the schema allows it)
Add a new enumeration value
Risky: old consumers may reject it
Make a required element optional
Yes for consumers that validate; may break code that expects it
Add a required element
No
Remove or rename an element
No
Change a type (string to integer) or tighten a facet
No
Change element order in an xs:sequence
No
Ways to Mark the Version
Version attribute on the root: <order version="1.2">. Good for minor, compatible changes; the namespace stays the same.
Namespace versioning: urn:acme:orders:v2. A new namespace signals a breaking change; every consumer must update, since element names change identity.
Schema location / file version: orders-1.2.xsd, published at a versioned URL.
Transport-level version: a header or URL (/api/v2/orders) for web services.
A common policy: major version in the namespace, minor version in an attribute.
Follow the “must ignore” rule: consumers ignore elements they do not understand, instead of failing.
XSD 1.1 adds open content (xs:openContent), which allows unknown elements more freely than 1.0 wildcards.
Running Versions Side by Side
Producers can emit the old version until all consumers upgrade, or emit the version a consumer asks for.
Transform between versions with XSLT at the boundary (an adapter that upgrades v1 documents to v2).
Deprecate elements with documentation and a removal date before deleting them.
Test compatibility in CI: validate sample v1 documents against the v2 schema, and the reverse.
Example Timeline
v1.0: <order version="1.0"> with id and total.
v1.1: adds optional <discount>; v1.0 consumers ignore it.
v2.0: total becomes a structure with currency, a breaking change, so it moves to namespace urn:acme:orders:v2; an XSLT adapter converts v1 messages during migration.
Pitfalls
Changing a schema in place without a version, which silently breaks partners.
Strict validation of incoming data with no wildcards, which blocks all additive change.
Too many namespace versions for small changes, forcing every consumer to update.
Interview Tip
Lead with the compatibility rules and the “must ignore” principle. Interviewers often ask how to add a field without breaking clients; the answer is an optional element plus tolerant consumers.
54
How does XML support internationalization and localization?
KnownRevise
Internationalization (i18n) in XML means designing documents and formats so they can hold any language and script, and localization (l10n) means producing language- or region-specific versions. XML supports this through Unicode (UTF-8/UTF-16 by default), the xml:lang attribute to tag content with a language, character references, locale-neutral XSD data types, and standards such as XLIFF and ITS for translation workflows.
Read full answerHide full answer
Applies toXML 1.0 (Fifth Edition), XML Schema 1.0/1.1, XLIFF 2.1 (OASIS), ITS 2.0 (W3C)
Built-In i18n Features
Unicode everywhere: XML text is Unicode, and UTF-8 or UTF-16 support is mandatory for every parser. Names can use non-Latin letters (<名前>).
Encoding declaration: <?xml version="1.0" encoding="UTF-8"?>; UTF-8 is the recommended choice.
Character references: ₹ (₹) for characters that are hard to type.
xml:lang: tags content with a BCP 47 language code (en, hi-IN, pt-BR); it is inherited by child elements.
xml:space: signals whether whitespace must be preserved, important for some scripts and poetry.
Bidirectional text (Arabic, Hebrew) is stored in logical order; display direction is handled by the rendering layer (for example a dir attribute in XHTML).
Selecting the Hindi name with XPath: //name[lang('hi')]. The lang() function also matches subtags such as hi-IN.
Locale-Neutral Data
Store data in canonical, locale-independent forms and format it only for display:
Data
Store as
Display (localized)
Date
2026-11-04 (xs:date)
4 November 2026 / 04/11/2026 / 11/4/2026
Decimal
1234.50 (xs:decimal)
1,234.50 / 1.234,50
Money
amount + ISO 4217 code (INR)
₹1,234.50
Time
2026-11-04T10:30:00+05:30
10:30 AM IST
Never store 04/11/2026, which means different dates in different countries.
Localization Workflow
XLIFF (XML Localization Interchange File Format) carries source text and translations between developers and translation tools.
ITS (Internationalization Tag Set) marks which parts of a document should be translated (its:translate="no") and adds notes for translators.
XSLT can choose the right xml:lang content and apply locale-specific formatting (format-date, format-number in XSLT 2.0+).
Best Practices
Use UTF-8 for all documents and declare it.
Use xml:lang instead of custom attributes such as language="english".
Keep translatable text in elements, not attributes, because elements can contain inline markup and are easier for translation tools to handle.
Avoid building sentences from fragments in code; word order differs between languages.
Keep data separate from presentation: canonical values in XML, formatting at display time.
Interview Tip
Mention xml:lang with inheritance, locale-neutral XSD types for dates and numbers, and XLIFF for translation workflows. A common mistake is storing pre-formatted, locale-specific dates and numbers, which breaks parsing and sorting.
55
What are the common XML Schema design patterns?
KnownRevise
The common XML Schema design patterns describe how element and type declarations are organized, mainly whether they are global (reusable) or local (nested). The four classic ones are Russian Doll, Salami Slice, Venetian Blind and Garden of Eden. Beyond them are patterns for extensibility and structure, such as wrapper elements, extension points with xs:any, and code lists.
Read full answerHide full answer
Applies toW3C XML Schema 1.0/1.1
The Four Classic Patterns
Pattern
Global elements
Global types
Reuse
Typical use
Russian Doll
Only the root
None (all anonymous, nested)
Low
Small, self-contained schemas
Salami Slice
All elements
None (anonymous types)
Elements
Element reuse; substitution groups
Venetian Blind
Only the root(s)
All named types
Types
Most enterprise schemas (recommended default)
Garden of Eden
All elements
All named types
Maximum
Large shared vocabularies (common in standards bodies)
Types are reusable and extensible (xs:extension), only order can be a root, and code generators produce clean classes. This is the usual recommendation.
Garden of Eden
All elements and all types global: maximum reuse and flexibility, at the cost of many possible roots and a large namespace surface.
Other Useful Patterns
Wrapper (container) elements for lists: <items><item/>...</items>. Easier to process and extend than repeated siblings mixed with other content.
Extension points: xs:any namespace="##other" processContents="lax" at the end of types for forward compatibility.
Code lists: enumerations in separate, versioned simple types (CountryCode, CurrencyCode), sometimes in their own module.
Abstract base type + substitution groups or xsi:type for polymorphic content (different payment methods).
Common types library: shared xs:imported module for address, money and identifiers.
Choosing a Pattern
Small, single-use schema: Russian Doll is fine.
Typical business messages: Venetian Blind.
Industry-wide vocabularies reused by many schemas: Garden of Eden or Salami Slice.
Interview Tip
Name the four patterns and explain them in terms of global vs local elements and types. The usual follow-up is which you would choose; Venetian Blind, with the reason “reusable types, a single root, good code generation”, is the expected answer.
56
What is XML data binding and what are its advantages?
KnownRevise
XML data binding automatically maps XML documents to typed objects in a programming language and back: unmarshalling (deserializing) turns XML into objects, marshalling (serializing) turns objects into XML. The mapping is defined by annotations or by classes generated from an XML Schema, so application code works with Order.getTotal() instead of DOM nodes, SAX events or XPath strings.
Read full answerHide full answer
Applies toJakarta XML Binding (JAXB) 4.0 for Java, .NET `XmlSerializer` / `xsd.exe`, Python `xsdata`, Jackson XML (`jackson-dataformat-xml`)
How It Works
Define the mapping:
Schema-first: generate classes from an XSD (xjc orders.xsd, xsd.exe /c orders.xsd, xsdata generate orders.xsd).
Code-first: annotate existing classes (@XmlRootElement, [XmlElement]) and optionally generate a schema.
Unmarshal incoming XML into objects, optionally validating against the schema.
Work with the objects in normal business code.
Marshal objects to XML for output.
Example in .NET
using System;
using System.IO;
using System.Xml.Serialization;
[XmlRoot("order")]
public class Order
{
[XmlAttribute("id")]
public string Id { get; set; } = "";
[XmlElement("customer")]
public string Customer { get; set; } = "";
[XmlElement("total")]
public decimal Total { get; set; } // decimal for money
}
public static class Program
{
public static void Main()
{
var serializer = new XmlSerializer(typeof(Order)); // cache and reuse this
const string xml = "<order id=\"42\"><customer>Asha</customer><total>1250.50</total></order>";
using var reader = new StringReader(xml);
var order = (Order)serializer.Deserialize(reader)!; // unmarshal
Console.WriteLine($"{order.Customer}: {order.Total}");
order.Total += 100m;
using var writer = new StringWriter();
serializer.Serialize(writer, order); // marshal
Console.WriteLine(writer);
}
}
Advantages
Productivity: far less code than DOM or SAX processing.
Type safety: compile-time checking; numbers and dates arrive already converted.
Contract alignment: schema-generated classes match the partner’s XSD exactly.
Readability and maintenance: business logic is not mixed with XML navigation.
Validation: many binders can validate during unmarshalling.
Tooling: IDE autocompletion, refactoring and unit testing of plain objects.
Disadvantages
Memory: the whole object graph is built; for very large files, stream with StAX or XmlReader and bind one record at a time.
Imperfect mapping: mixed content, xs:any, substitution groups and complex xs:choice structures map awkwardly.
Schema changes require regenerating classes and redeploying.
Lost details: comments, processing instructions, attribute order and formatting are usually not preserved, which matters for signed documents.
Performance overhead of reflection, unless the library generates code or caches metadata.
When to Use It
Business messages with a stable schema (orders, invoices, SOAP payloads).
Configuration files read into typed settings.
Not for document-style content with rich mixed markup, or for editing documents where exact formatting must be kept.
Security
Disable DTD processing for untrusted input (for example XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit } passed to Deserialize through an XmlReader), and never let input choose arbitrary types to instantiate.
Interview Tip
Explain schema-first vs code-first and the memory trade-off. A common mistake is creating a new serializer or binding context for each request; they are expensive and meant to be cached.
57
What is XML validation and how is it performed?
KnownRevise
XML validation checks that a well-formed document also conforms to a schema, which defines the allowed elements and attributes, their order and cardinality, and their data types. It is performed by a validating parser or validator that loads a DTD, an XML Schema (XSD), RELAX NG or Schematron rules and reports every violation, so bad data is rejected at the system boundary.
Read full answerHide full answer
Applies toDTD (XML 1.0), W3C XML Schema 1.0/1.1, RELAX NG (ISO/IEC 19757-2), Schematron (ISO/IEC 19757-3)
Purpose
Enforce contracts between systems and partners (orders, invoices, government filings).
Catch errors early: a missing customer ID or quantity="abc" fails at the edge, not deep in business logic.
Reduce defensive code: after validation, code can rely on the structure and types.
Document the format: the schema is a precise, machine-checkable specification.
Security: reject unexpected structures and oversized values before processing.
Schema Languages
Language
Strength
Typical use
DTD
Simple; declares entities
Legacy formats
XSD 1.0 / 1.1
Data types, namespaces, keys; 1.1 adds assertions
Most enterprise and standards formats
RELAX NG
Compact, readable, flexible content models
Document formats (DocBook 5, ODF)
Schematron
XPath rules across fields
Business rules: “end date after start date”
A common combination is XSD for structure plus Schematron for business rules.
How It Is Performed
Parse the document and check well-formedness.
Load the schema (configured in code, or via xsi:schemaLocation hints).
Validate each element and attribute against its declaration and type.
Collect errors with line and column numbers.
Reject or quarantine invalid documents.
Example in Python (lxml)
from lxml import etree
schema = etree.XMLSchema(etree.XML(b"""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
<xs:complexType>
<xs:sequence><xs:element name="total" type="xs:decimal"/></xs:sequence>
<xs:attribute name="id" type="xs:positiveInteger" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>"""))
for doc in [b'<order id="42"><total>99.50</total></order>',
b'<order id="abc"><total>lots</total></order>']:
tree = etree.fromstring(doc)
if schema.validate(tree):
print("valid")
else:
for err in schema.error_log:
print("invalid:", err.message)
In Java the equivalent is SchemaFactory.newSchema(...).newValidator().validate(source); in .NET, XmlReaderSettings with ValidationType.Schema.
Best Practices
Validate at trust boundaries (incoming partner messages, uploads); internal hops may skip it for speed.
Load schemas from local files or a catalog, never from URLs in the incoming document.
Compile schemas once and reuse them; compiled schema objects are usually thread-safe.
Report all errors with locations to help the sender fix their data.
Version schemas and keep tests with valid and invalid sample documents.
Pitfalls
Assuming the parser validates automatically: most parsers only check well-formedness unless validation is enabled.
Trusting xsi:schemaLocation from untrusted input, which lets an attacker choose the schema.
DTD validation on untrusted input without disabling external entities (XXE risk).
Interview Tip
Separate well-formedness (syntax) from validity (schema), and say where you would validate. Mentioning Schematron for cross-field rules shows you know XSD’s limits.
58
What techniques are used to transform XML data?
KnownRevise
XML data transformation converts XML from one structure or format into another, for example from a partner’s order format into your internal one, from XML to HTML for display, or from XML to JSON or CSV. The main techniques are XSLT (declarative, template-based), XQuery (query and construct), programmatic transformation with DOM, streaming APIs or data binding, and integration-platform mapping tools that generate these underneath.
Read full answerHide full answer
Applies toXSLT 1.0–3.0, XQuery 3.1, common XML APIs (JAXP, .NET `System.Xml`, Python `lxml`)
Why Transformations Are Needed
Integration: two systems use different schemas for the same business data.
Presentation: render XML as HTML, PDF (through XSL-FO) or text reports.
Format conversion: XML to JSON for web clients, or CSV for spreadsheets.
Versioning: upgrade v1 documents to the v2 schema.
Filtering and enrichment: remove sensitive fields, add computed values.
XSLT when the mapping is mostly structural and you want it outside application code; use XSLT 3.0 (Saxon) for grouping, JSON output and streaming.
Streaming code for multi-GB files with simple mappings, or XSLT 3.0 streaming.
Data binding when the transformation needs business rules or database lookups.
XQuery when data comes from an XML database or several documents must be joined.
Best Practices
Keep mappings in version control with test fixtures (input, expected output).
Validate input before and output after transforming.
Use the identity transform plus overrides for “copy almost everything” changes.
Never run untrusted stylesheets with extension functions enabled.
Interview Tip
Name XSLT as the standard tool, but show you would choose based on size, complexity and where the rules should live. A common mistake is string-concatenating XML in code, which breaks escaping and namespaces.
59
How do you optimize XML processing performance?
KnownRevise
XML performance is optimized by choosing the right parsing model (streaming for large documents), reusing expensive objects (parser factories, compiled schemas and stylesheets), avoiding unnecessary work (repeated parsing, needless validation, // searches), keeping documents compact, and measuring before and after each change. The biggest gains usually come from not building a full DOM for huge files and not recompiling schemas or XSLT on every request.
Read full answerHide full answer
Applies togeneral practice across Java (JAXP, StAX), .NET (`XmlReader`), Python (`lxml`, `iterparse`)
Parsing
Stream large documents with SAX, StAX, XmlReader or iterparse, keeping memory constant; DOM memory can be several times the file size.
Use the hybrid pattern: stream, build a small tree per record, then discard it (elem.clear()).
Choose fast libraries: lxml (libxml2) is much faster than pure-Python parsers; Aalto or Woodstox are fast StAX implementations in Java.
Turn off features you do not need: DTD loading, external entity resolution and namespace processing when the format has none. Disabling DTDs also improves security.
Parse once: pass the parsed tree or objects between components rather than re-serializing and re-parsing.
Avoid // on large trees; use explicit paths (/orders/order/total).
Compile and reuse XPath expressions instead of evaluating strings repeatedly.
In XSLT, use keys (xsl:key and key()) for lookups instead of repeated searches.
Use XSLT 3.0 streaming (Saxon-EE) for transformations over very large inputs.
Document Design
Avoid deep nesting and very long names in high-volume messages.
Do not embed large binary data as Base64 in XML; store it elsewhere and send a reference (or use MTOM for SOAP).
Compress on the wire: gzip typically shrinks XML by 80–90% because tags repeat.
For internal high-throughput services, consider a binary format (Protocol Buffers, EXI for XML).
Validation
Validate at the trust boundary, not at every internal hop.
Validate while streaming (validator on a SAX/StAX source) instead of building a DOM first.
Use local schema copies via XML Catalogs; never fetch schemas over the network at runtime.
Example: Streaming Instead of DOM
import io
import xml.etree.ElementTree as ET
def total_value(stream) -> float:
total = 0.0
for _, elem in ET.iterparse(stream, events=("end",)):
if elem.tag == "item":
total += float(elem.get("price")) * int(elem.get("qty"))
elem.clear() # keep memory flat
return total
data = io.BytesIO(b"<items>" + b'<item price="2.5" qty="4"/>' * 100_000 + b"</items>")
print(total_value(data)) # 1000000.0
Measure
Profile with realistic file sizes (async-profiler, dotnet-trace, cProfile). Track parse time, memory peak and GC activity, since the bottleneck is often not where you expect.
Interview Tip
Mention streaming vs DOM, reuse of compiled schemas and stylesheets, and compression. A common mistake is compiling an XSLT or schema on every request, which can cost more than the transformation itself.
60
What are the key security considerations when processing XML?
KnownRevise
XML security has two sides: protecting the system that parses XML from malicious documents (XXE, entity expansion, oversized input, injection), and protecting the data inside XML (integrity with XML Signature, confidentiality with XML Encryption, plus TLS in transit). The most important single rule is: disable DTD processing and external entities for untrusted input.
Read full answerHide full answer
Applies toXML 1.0 parsers in all major platforms; W3C XML Signature 1.1 and XML Encryption 1.1
Parser Attacks
Attack
How it works
Defence
XXE (XML external entity)
<!ENTITY x SYSTEM "file:///etc/passwd"> makes the parser read local files or call internal URLs (SSRF)
Disallow DOCTYPE, disable external entities
Billion laughs (entity expansion)
Nested entities expand a few KB into GBs, exhausting memory
Disable DTDs or limit entity expansion
Quadratic blowup
One large entity referenced many times
Same as above
Oversized input
Huge documents, deep nesting, very long attribute values
Untrusted stylesheets call extension functions or read files
Never run untrusted XSLT; disable extensions
Safe Parser Configuration
Java: factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true), enable XMLConstants.FEATURE_SECURE_PROCESSING, set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to "".
.NET: XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null } (modern .NET defaults are safe for XmlReader).
Python: use defusedxml for untrusted input.
PHP / libxml2: do not enable LIBXML_NOENT or LIBXML_DTDLOAD for untrusted data.
from defusedxml.ElementTree import fromstring
from defusedxml import DTDForbidden, EntitiesForbidden
evil = '<?xml version="1.0"?><!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]><r>&x;</r>'
try:
fromstring(evil, forbid_dtd=True)
except (DTDForbidden, EntitiesForbidden) as e:
print("rejected:", type(e).__name__) # rejected: DTDForbidden
Injection
XML injection: building XML by string concatenation lets input like </name><admin>true</admin> change the structure. Always build XML with a library that escapes values.
XPath injection: "//user[name='" + input + "']" can be bypassed with ' or '1'='1. Use parameterized XPath (variables) or strict input validation.
Protecting the Data
Integrity and authenticity: XML Signature with RSA-SHA256 or ECDSA; verify the certificate chain and guard against signature wrapping (check that the element you use is the one that was signed).
Confidentiality: XML Encryption 1.1 with AES-GCM and RSA-OAEP; avoid AES-CBC (padding-oracle attacks) and RSA PKCS#1 v1.5.
In transit: TLS 1.2+ (prefer 1.3) for every connection.
Sensitive data: do not put secrets in comments or log full documents.
Operational Practices
Validate untrusted documents against local schemas at the boundary.
Keep XML libraries updated; parser CVEs are common.
Add XXE and entity-expansion payloads to security tests.
Interview Tip
Lead with XXE and its fix, then entity expansion, then injection, then signature and encryption. Interviewers often ask for the exact parser setting; naming disallow-doctype-decl or defusedxml shows hands-on experience.
61
How does XML Signature guarantee data integrity?
KnownRevise
XML Signature guarantees integrity by hashing the signed data and then signing those hashes with the signer’s private key. Each signed resource gets a digest (for example SHA-256) stored in a <ds:Reference>; the <ds:SignedInfo> block containing all references is canonicalized and signed. A verifier recomputes every digest and checks the signature with the public key, so any change to the signed content or to the references makes verification fail.
Read full answerHide full answer
Applies toW3C XML Signature Syntax and Processing 1.1
The Integrity Chain
Select the data to protect with Reference URI="#order-42" (or the whole document, or an external file).
Transform it: remove the signature element itself (enveloped-signature transform) and canonicalize it, so formatting differences do not matter.
Digest it: compute SHA-256 over the canonical bytes and store the result in DigestValue.
Canonicalize SignedInfo, which contains the references, digests and algorithm names.
SignSignedInfo with the private key and store the result in SignatureValue.
Verification
Canonicalize SignedInfo and verify SignatureValue with the signer’s public key. This proves SignedInfo (and so every digest in it) is unchanged and came from the key holder.
For each Reference, apply the same transforms, recompute the digest and compare it with DigestValue. This proves the referenced data is unchanged.
Validate the signer’s certificate against a trust store.
If one byte of the canonical content changes, its digest changes; if someone edits a digest to match, the signature over SignedInfo no longer verifies.
Why Canonicalization Matters
XML can be re-serialized in many equivalent ways (attribute order, quote style, namespace declarations). Without canonicalization, a harmless re-serialization by a proxy or library would break the digest. Exclusive canonicalization is preferred for fragments that move between documents (SAML, SOAP).
What Integrity Does and Does Not Cover
Covered
Not covered
Content of each referenced node or resource
Parts of the document not referenced
The algorithms and references listed in SignedInfo
Confidentiality (use XML Encryption or TLS)
Origin, if the key is trusted
Freshness: replay protection needs timestamps or nonces
The Signature Wrapping Pitfall
Integrity only protects what was signed. In a signature wrapping attack, the attacker leaves the signed element intact (so verification passes) but moves it, and inserts a forged element where the application actually reads data. Defences:
After verification, process only the nodes the signature covered, obtained from the verification API, rather than looking them up again by XPath.
Reject duplicate IDs and unexpected document structures; validate against a strict schema first.
Sign the whole message or assertion, not small fragments.
Algorithms
Digest: SHA-256 or stronger. Do not accept SHA-1 or MD5.
Signature: RSA-SHA256 (2048-bit keys or larger) or ECDSA-SHA256.
Restrict transforms to the expected set; disallow XSLT and XPath filter transforms from untrusted senders.
Interview Tip
Explain the two levels: digests protect the data, the signature protects the digests. Then mention canonicalization and wrapping attacks; those details separate a strong answer from a textbook definition.
62
How does XML Encryption keep data confidential?
KnownRevise
XML Encryption keeps data confidential by replacing sensitive parts of an XML document (an element, its content, or the whole document) with an <xenc:EncryptedData> element holding ciphertext, so only holders of the right key can recover the original. It uses hybrid encryption: the data is encrypted with a fast symmetric key (AES-GCM), and that key is encrypted for each recipient with their public key (RSA-OAEP) or a shared key-wrapping key.
Read full answerHide full answer
Applies toW3C XML Encryption Syntax and Processing 1.1
Its Role in Confidentiality
Selective encryption: encrypt only the card number or diagnosis; routing and metadata stay readable to intermediaries.
End-to-end, message-level protection: data stays encrypted across queues, gateways, logs and storage. TLS only protects each network hop and ends at every server that terminates it.
Multiple recipients: one content key can be wrapped for several recipients, or different parts encrypted for different parties.
Persistent protection: encrypted XML can be stored and still be protected later.
XML Encryption vs TLS
Aspect
TLS
XML Encryption
Protects
The connection, hop by hop
The data itself, end to end
Granularity
Whole stream
Element, content or document
Intermediaries
See plaintext after TLS ends
See only ciphertext
Stored data
Not protected
Stays encrypted
Complexity
Low (standard infrastructure)
Higher: keys per recipient, libraries
In practice you use both: TLS for transport, XML Encryption for data that must stay protected beyond one hop.
Example Flow: Encrypted SAML Assertion
The identity provider builds an assertion with user attributes.
It generates a random AES-256 key and encrypts the assertion with AES-256-GCM.
It encrypts that AES key with the service provider’s RSA public key (RSA-OAEP).
It sends <saml:EncryptedAssertion> containing EncryptedData and EncryptedKey.
Only the service provider’s private key can unwrap the AES key and decrypt the assertion; the browser that relays it sees only ciphertext.
Key Elements
Element
Contains
xenc:EncryptedData
Algorithm, key info and CipherValue of the data
xenc:EncryptedKey
The wrapped content-encryption key for a recipient
xenc:EncryptionMethod
Algorithm URI (e.g. http://www.w3.org/2009/xmlenc11#aes256-gcm)
ds:KeyInfo
Which key to use (certificate, key name, EncryptedKey)
Security Requirements
Use AES-GCM (XML Encryption 1.1). The 1.0 CBC modes allowed practical padding-oracle attacks against web services (published in 2011).
Use RSA-OAEP, not RSA PKCS#1 v1.5, for key transport.
Do not leak error details: return one generic error for every decryption or parsing failure, so attackers cannot use responses as an oracle.
Add integrity: GCM authenticates the ciphertext, but signatures may still be needed to prove who created the data. Decide the order (sign then encrypt, or encrypt then sign) consistently.
Protect keys: private keys in an HSM or key vault, with rotation.
Use proven libraries (Apache Santuario, xmlsec, .NET EncryptedXml); never write your own crypto.
Interview Tip
Explain why message-level encryption is needed when TLS already exists: intermediaries and storage. Naming AES-GCM, RSA-OAEP and the CBC padding-oracle history shows depth.
63
How is an XML Digital Signature created?
KnownRevise
An XML Digital Signature proves that XML data has not been changed and identifies who signed it. It is created by canonicalizing and hashing each piece of data to protect, recording those digests in a <ds:SignedInfo> element, then signing the canonicalized SignedInfo with the signer’s private key and storing the result in <ds:SignatureValue>, together with key information such as an X.509 certificate.
Read full answerHide full answer
Applies toW3C XML Signature 1.1; examples use the Java XML Digital Signature API (`javax.xml.crypto.dsig`, part of the JDK)
Purpose
Integrity: detect any change to the signed data.
Authenticity: show the data came from the private-key holder.
Non-repudiation: with a trusted certificate, the signer cannot easily deny it.
Used in SAML single sign-on, WS-Security, e-invoicing, XAdES legal e-signatures and signed configuration files.
Creation Steps
Choose what to sign: the whole document (URI=""), an element by ID (URI="#inv-7"), or an external resource.
Choose the signature form: enveloped (inside the document, most common), enveloping, or detached.
Define transforms: usually enveloped-signature (exclude the signature itself) plus exclusive canonicalization.
Compute the digest of the transformed data with SHA-256 and place it in a Reference.
Build SignedInfo with the canonicalization method, signature algorithm and all references.
Canonicalize and sign SignedInfo with the private key (RSA-SHA256 or ECDSA-SHA256).
Add KeyInfo (certificate or key name) and insert <ds:Signature> into the document.
Code Example (Java, Enveloped Signature)
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import org.w3c.dom.Document;
public class XmlSigner {
public static void sign(Document doc, PrivateKey key, X509Certificate cert) throws Exception {
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference(
"", // sign the whole document
fac.newDigestMethod(DigestMethod.SHA256, null),
List.of(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null),
fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)),
null, null);
SignedInfo si = fac.newSignedInfo(
fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA256, null),
Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyInfo ki = kif.newKeyInfo(List.of(kif.newX509Data(List.of(cert))));
DOMSignContext ctx = new DOMSignContext(key, doc.getDocumentElement()); // signature goes in the root
fac.newXMLSignature(si, ki).sign(ctx); // computes digest + SignatureValue
}
}
The library performs the canonicalization, hashing and signing; your code chooses what to sign and with which algorithms.
Verification (Briefly)
The receiver canonicalizes SignedInfo, checks SignatureValue with the public key, recomputes each reference digest, and validates the certificate chain against its own trust store.
Best Practices
Strong algorithms: SHA-256+ digests; RSA 2048-bit+ or ECDSA. No SHA-1.
Sign before any formatting changes: pretty-printing after signing breaks the signature.
Protect the private key (HSM, key vault) and rotate certificates.
Prefer signing whole messages or assertions; on verification, use only the nodes that were signed to avoid wrapping attacks.
Interview Tip
Walk through reference, digest, SignedInfo and signature value in order. A common mistake is saying the whole document is “encrypted with the private key”; the signature is over SignedInfo, which contains digests of the data.
64
What is XML Key Management (XKMS) and why does it matter?
KnownRevise
XML Key Management Specification (XKMS) is a W3C standard defining XML-based web-service protocols for registering, locating and validating public keys. Its goal was to let applications that use XML Signature and XML Encryption hand the complex work of PKI (certificate parsing, chain building, revocation checking) to a trusted service. Version 2.0 became a W3C Recommendation in 2005, but it saw little adoption, so today it matters mostly as a concept: centralizing key management behind a service.
Read full answerHide full answer
Applies toXKMS 2.0 (W3C Recommendation, 2005); modern equivalents include cloud key-management services and certificate-validation services
The Problem It Addresses
XML Signature and Encryption need keys:
A verifier receives a signature with <ds:KeyInfo> and must decide whether that key is trusted, not expired and not revoked.
An encrypting sender must find the recipient’s current public key.
Doing this in every client means implementing X.509 path validation, CRL or OCSP checks and trust stores, which is complex and error-prone.
The Two Parts
Part
Purpose
Main operations
X-KISS (Key Information Service Specification)
Find and validate keys
Locate (find a key for a name or usage), Validate (is this key trusted and valid?)
X-KRSS (Key Registration Service Specification)
Manage the key lifecycle
Register, Reissue, Revoke, Recover
How It Works
A client receives a signed document with a KeyInfo element.
It sends an XKMS ValidateRequest (a SOAP message) containing that key information to a trusted XKMS service.
The service does the PKI work: builds the certificate chain, checks revocation and policy.
It returns a ValidateResult with the key’s status (Valid, Invalid or Indeterminate) and its bound names and usages.
The client accepts or rejects the signature.
Why It Is Important (as a Concept)
Simpler clients: thin clients and devices need only XML and SOAP, not a PKI toolkit.
Centralized policy: one service decides which certificate authorities are trusted and how revocation is checked.
Lifecycle management: registration, renewal and revocation are standardized operations.
Consistency across applications in an organization.
SOAP-based infrastructure lost ground to REST and JSON.
Organizations moved to other approaches: OCSP for revocation, LDAP directories, and later cloud services such as AWS KMS, Azure Key Vault and HashiCorp Vault.
Enterprise PKI and certificate management (ACME, internal CAs)
Centralized key policy
Key-management services and HSMs
Interview Tip
Be accurate: describe XKMS, its X-KISS and X-KRSS parts, and the goal of offloading PKI complexity. Then say honestly that it is rarely deployed today and name what replaced it. Claiming it is widely used is a common mistake.
65
What role does XML play in web services and SOA?
KnownRevise
In web services and service-oriented architecture (SOA), XML is the common data and contract format: SOAP messages are XML envelopes, WSDL describes service interfaces in XML, XSD defines the message types, and the WS-* standards (WS-Security, WS-Addressing, WS-ReliableMessaging) are all XML vocabularies. This gives SOA platform-neutral, strongly typed, machine-readable contracts between services built in different technologies.
Read full answerHide full answer
Applies toSOAP 1.1/1.2, WSDL 1.1/2.0, XML Schema 1.0, WS-Security 1.1 (OASIS); ESB and integration platforms
Where XML Appears
Role
Standard
What it does
Message format
SOAP
Envelope with optional Header and a Body carrying the payload
Service contract
WSDL
Operations, messages, bindings and endpoints
Data types
XSD
Exact structure and types of requests and responses
Interoperability: Java, .NET, mainframes and packaged applications can all produce and consume it.
Contract-first design: WSDL and XSD define the interface before code; tools generate client and server stubs.
Strong validation: messages can be checked against the schema at the boundary.
Extensibility: namespaces and SOAP headers let standards add security and routing without changing payloads.
Message-level security: XML Signature and Encryption protect parts of a message across intermediaries.
Trade-offs
Verbose and slower to parse than JSON or binary formats; larger messages cost bandwidth and CPU.
Complexity: the WS-* stack is large and interoperability between toolkits needed careful profiles (WS-I Basic Profile).
Tight coupling to generated stubs: schema changes often require regenerating clients.
Today
New public and internal APIs mostly use REST with JSON or gRPC with Protocol Buffers, described by OpenAPI or .proto files.
XML-based SOA remains common in banking, insurance, telecom, government, healthcare and ERP integration, where WS-Security, formal contracts and existing systems matter.
Many architectures mix them: an API gateway exposes JSON REST and translates to SOAP for legacy back ends.
Interview Tip
Map each XML standard to its role (SOAP = message, WSDL = contract, XSD = types, WS-Security = protection). Then be balanced: say when you would still choose SOAP (formal contracts, message-level security, existing partners) and when REST/JSON is better.
66
How do SOAP and REST use XML?
KnownRevise
SOAP is an XML-based messaging protocol: every request and response is an XML envelope, described by a WSDL contract and XSD types. REST is not an XML protocol but an architectural style built on HTTP resources, methods and status codes; a REST API can exchange XML representations (Content-Type: application/xml), though most use JSON today.
Read full answerHide full answer
Applies toSOAP 1.2 (W3C), WSDL 1.1/2.0, REST as described by Roy Fielding (2000), HTTP semantics (RFC 9110)
SOAP: XML at the Core
Envelope: <soap:Envelope> with an optional <soap:Header> (security, routing, transactions) and a <soap:Body> (the payload or a <soap:Fault> for errors).
Contract: WSDL defines operations, messages and endpoints; XSD defines the types.
Transport-independent: usually HTTP POST, but also JMS or SMTP.
WebDAV: HTTP extensions with XML request and response bodies.
Atom Publishing Protocol: RESTful publishing with Atom XML.
When to Choose Which
SOAP: formal contracts with partners, message-level security across intermediaries, reliable messaging, or existing SOAP ecosystems.
REST (with JSON): most new web and mobile APIs; simpler, cacheable, lighter.
REST with XML: when clients need XML (document formats, existing XSD-based data standards) but you want REST semantics.
Interview Tip
Correct the premise politely: SOAP is XML-based; REST is format-agnostic. Interviewers value the protocol vs architectural-style distinction and a reasoned choice, not “REST is always better”.