XML interview question · Most asked
Explain XPath axes and give examples of predicates.
Summary
An axis sets the direction of a step: child (default), attribute (@), descendant (//), parent (..), ancestor, following-sibling, preceding-sibling, following, preceding, self. Predicates filter: //product[price > 10], //item[@sku='A1'], //product[last()], //p[contains(name, 'tea')].
Longer Answer
Watch for //product[1] (first product of each parent) vs (//product)[1] (first in the document), and node-set comparisons that are true if any node matches.
Key Points
- Axes set direction.
- Predicates filter.
- Positions start at 1.
- (//x)[1] vs //x[1].
Deep dive: XML Tutorial: XPath Axes and Functions
Explanation
What interviewers look for
Correct axes and the position pitfall.
More most-asked XML questions
- What's the difference between well-formed and valid XML?
- Explain XML namespaces and the default namespace.
- Compare DOM, SAX and StAX (or pull parsing).
- Your XPath query returns nothing, but the elements are clearly there. What's the likely cause?
- What is an XXE attack and how do you prevent it?
- What is XML and where is it still used today?
- Which characters must be escaped in XML, and what is CDATA?
- Compare DTD, XML Schema (XSD), RELAX NG and Schematron.