Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

XML: schema, DTD, XPath and XQuery

Clear, exam-focused notes on XML structure and validation (DTDs and XML Schema), plus querying with XPath and XQuery, aimed at computer engineering undergraduates.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

XML (eXtensible Markup Language) is a plain-text, platform-independent format used to represent structured data. Engineers use XML for configuration, data interchange (APIs), and intermediate formats; understanding validation (DTDs and XML Schema) and querying (XPath and XQuery) is essential for building robust pipelines and integrating systems.

Key ideas

Start from first principles and define each term before use.

  • XML (eXtensible Markup Language) — a text format for hierarchical, tree-structured data made of elements, attributes, and text nodes. It requires a single root element and must be well-formed to be processed by XML parsers.
  • Well-formed — an XML document is well-formed if it obeys syntax rules: single root, properly nested elements, start and end tags match, attributes quoted, and no overlapping tags.
  • Valid — a well-formed XML document is valid if it conforms to a schema (either a DTD or an XML Schema Definition (XSD)). Validation enforces structure and types.

Document Type Definition (DTD)

  • DTD (Document Type Definition) — a textual specification of the allowed elements, their hierarchy (content models), and attributes for an XML document. A DTD can be internal (inside the XML file) or external (separate file referenced by DOCTYPE).
  • Exact statement (definition exam style): A DTD consists of element declarations, attribute-list declarations, entity declarations and notation declarations. Element declarations use regular-expression-like operators: ? (zero or one), * (zero or more), + (one or more), , (sequence), and | (choice). Element content can also be declared as EMPTY (no content) or ANY, and text content with #PCDATA; mixed content uses the form <!ELEMENT p (#PCDATA | em | strong)*>.
  • Example content model syntax to be able to draw/describe: To declare an element book with a sequence of title, one or more author, and optional isbn, write <!ELEMENT book (title, author+, isbn?)>.
  • Attributes in DTD: declared with <!ATTLIST element-name attr-name type default>; attribute types include CDATA, ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS, NOTATION, and enumerations (e.g., (hardcover|paperback)). Default options: #REQUIRED, #IMPLIED, "default", #FIXED "value".

XML Schema (XSD)

  • XML Schema Definition (XSD) — an XML-based language to define the structure, datatypes, default values and namespaces of XML documents. XSD is more expressive and type-rich than DTD.
  • Simple type — a type that contains text only (no child elements); examples: xs:string, xs:integer, xs:date. Complex type — a type that may contain child elements and/or attributes.
  • Exact statements: XSD supports derivation by restriction and extension. Restriction reduces the set of values (for simple types) or allowed children (for complex types); extension adds new elements/attributes to a base complex type.
  • XSD uses XML namespace http://www.w3.org/2001/XMLSchema and element names like xs:element, xs:complexType, xs:simpleType, xs:sequence, xs:choice, xs:attribute, and facets xs:minInclusive, xs:maxLength, etc. In instance documents, the http://www.w3.org/2001/XMLSchema-instance namespace (prefix xsi) is used for xsi:type, xsi:nil, and schema location hints.
  • Describe what to draw: Draw a tree (root element) labelled catalog with child element book repeating (use maxOccurs="unbounded"), inside each book draw title, author (may repeat), price with xs:decimal type. Next to price note facets minInclusive and totalDigits if constrained.

Namespaces

  • Namespace — a URI used to disambiguate element and attribute names from different vocabularies. In XML use xmlns or xmlns:prefix="URI". Qualified names (QNames) use the prefix (e.g., bk:title) to reference a namespace. Note: the default namespace applies to unprefixed elements, not to attributes.

XPath

  • XPath (XML Path Language) — a language for selecting nodes from an XML document. XPath expressions are used in XSLT, XQuery and many APIs.
  • Key concepts: node (document/root, element, attribute, text, comment, processing-instruction, namespace), axis (relationship to current node: child, descendant, parent, following-sibling, etc.), node test (element name or node(), text()), and predicate (filter in [...]).
  • Exact syntax elements students must know: absolute path starts with /, relative path does not, // means descendant-or-self axis shortcut, @ selects attributes, predicates can use boolean and positional filters (e.g., [position()=1], [price>50]).

XQuery

  • XQuery — a functional language to query and transform XML data. It extends XPath with FLWOR expressions (For-Let-Where-Order by-Return), functions, and XML construction.
  • FLWOR pattern: for $x in expr1 let $y := expr2 where condition order by keys return expr3. for iterates over sequences, let binds values, where filters, order by sorts, and return constructs output.
  • XQuery supports path expressions, atomic types, and user-defined functions. It can produce new XML by using element constructors: <person>{ $name }</person>.

What to draw for a diagram question

  • For DTD/XSD: draw a tree showing allowed children and multiplicities (use labels like 0..1, 1.., 0..). For namespaces: draw two elements with same local name but different prefixes pointing to different URI boxes.

Assumptions behind each definition: DTDs do not support XML namespaces or rich datatypes; XSD does support namespaces and typed content. XPath 1.0 has limited type handling; XPath 2.0/XQuery use sequences and richer types.

Formulas

(Syntax and short patterns to remember)

<!DOCTYPE root SYSTEM "file.dtd"> — Declares external DTD; root is document root name.

<!ELEMENT name (child1, child2?, child3+) > — Element declaration in DTD. ?, *, + as in regular expressions.

<!ATTLIST element attr CDATA #REQUIRED> — Attribute declaration in DTD.

<xs:element name="book" type="BookType"/> — XSD element declaration (use namespace prefix e.g. xs).

<xs:complexType name="BookType"><xs:sequence>...</xs:sequence></xs:complexType> — complexType with child sequence.

<xs:simpleType name="ISBN"><xs:restriction base="xs:string"><xs:pattern value="\d{13}"/></xs:restriction></xs:simpleType> — simpleType with pattern facet.

XPath basics: /root/child — select child element named child of root. //book — select all book elements anywhere (descendants). /catalog/book[price>30] — select book elements with price > 30. /catalog/book[author[1]] — book with at least one author. @id — attribute id of current node.

XQuery FLWOR pattern: for $b in doc("books.xml")/catalog/book where $b/price>30 order by $b/price descending return <expensive>{$b/title, $b/price}</expensive>

Explain symbols where necessary in the lines above in the Key ideas section; units not applicable.

Worked examples

  1. Validate XML with a DTD (step-by-step). Given XML:
<catalog> <book id="b1"> <title>Intro to DB</title> <author>Alice</author> </book> </catalog>

And DTD: <!ELEMENT catalog (book+)><!ELEMENT book (title, author+)><!ATTLIST book id ID #REQUIRED> Steps:

  • Check well-formedness: single root catalog, tags balanced — OK.
  • Check validity: catalog must contain one or more book — XML has one book — OK.
  • book must have title followed by one or more author — XML has title then one author — OK.
  • book has required attribute id of type ID — present and unique (assume unique in doc) — OK. Document is valid.
  1. XPath selection trace. XML fragment:
<catalog> <book id="b1"><title>DB</title><price>50</price></book> <book id="b2"><title>OS</title><price>40</price></book> </catalog>

Expression: /catalog/book[price>45]/@id Trace steps:

  • /catalog selects root element catalog.
  • /catalog/book yields two book nodes (b1, b2).
  • [price>45] filters to those with a child price node whose numeric value > 45 -> only b1.
  • /@id selects the id attribute of b1 -> returns b1. Answer: attribute node with value b1.
  1. XQuery FLWOR example. Task: produce <item><name>...</name><cost>...</cost></item> for books priced >45. XQuery: for $b in doc("books.xml")/catalog/book where xs:decimal($b/price) > 45 return <item>{<name>{data($b/title)}</name>, <cost>{data($b/price)}</cost>}</item>

Trace on same XML: book b1 price 50 -> included -> returns <item><name>DB</name><cost>50</cost></item>; b2 excluded.

Common mistakes

  • Forgetting to quote attribute values in element tags (breaks well-formedness).
  • Using / vs // incorrectly in XPath; /a//b is not the same as /a/b.
  • In XQuery, returning node constructors without data() when scalar is needed; forgetting fn:doc() or doc() to load external XML.
  • Misusing position() in predicates — book[position()=1] selects first book in that node-set, not globally first.

For your exam

Kinds of questions:

  • Definitions: define DTD, XSD, XPath, XQuery — include syntax and purpose.
  • Short notes: compare DTD vs XSD, namespaces, XPath axes, FLWOR semantics.
  • Derivations: show how to derive a complexType by extension/restriction in XSD; explain implications for validation.
  • Programs/queries: write XPath to select nodes, or XQuery to transform data; trace the given query on sample XML.
  • Diagrams: draw an element tree with multiplicities and annotations for types.

What full-marks answers include:

  • Clear definitions (bold term and its formal statement), correct syntax or declaration, and explanation of assumptions (e.g., DTD lacks namespaces).
  • For queries: full code with path expressions, explanation of each clause, and a worked trace on supplied XML.
  • For validation: show step-by-step checking of element order, occurrences, and attribute requirements.

Quick check

  1. What is the difference between well-formed and valid XML?
  2. In DTD, what does ID attribute type enforce?
  3. Write an XPath to select the title of every book with price > 100.

Answers: 1) Well-formed means XML syntax rules satisfied; valid means it also conforms to a DTD or XSD. 2) ID enforces uniqueness and that the value is a valid XML name, and can be referenced by IDREF. 3) /catalog/book[price>100]/title

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?