XML (eXtensible Markup Language) stores and transports data using tags you invent. Well-formedness rules, validation with DTDs or XML Schema, DOM vs SAX parsing, and XPath/XSLT transformations are core exam topics.
High-yield 65 minSyllabus: “XML”
Mark as
The idea in one minute
HTML is a fixed set of labels for how a page looks — heading, paragraph, table. XML is a label-maker: you print whatever labels your data needs — scheme, district, units — and stick them on. A DTD or schema is the rulebook saying which labels may appear, in what order and how often; a parser is the inspector who checks the labels; XSLT is a machine that relabels the boxes into an HTML page.
Key points — the night-before list
XML describes and carries data with user-defined, case-sensitive tags; HTML presents data with predefined tags. XML 1.0 became a W3C Recommendation in 1998.
Well-formed: one root, every tag closed, proper nesting, matching case, quoted attribute values, no duplicate attributes, < and & escaped in text.
Valid = well-formed and conforms to a DTD or XML Schema. Every valid document is well-formed, not vice versa.
Five predefined entities: <>&'". CDATA sections hold text that is not parsed for markup.
XML Schema (XSD) is itself XML, has data types (xs:integer, xs:date…), namespaces, minOccurs/maxOccurs (both default 1) and facets such as pattern and maxInclusive.
DOM builds the whole tree in memory (random access, editable); SAX streams events to callbacks (fast, low memory, read-only, forward-only); StAX is a pull parser.
XPath selects nodes (//scheme[units > 50], positions start at 1); XSLT transforms XML into HTML or other XML; XSL-FO formats it for print.
01Why XML: describing data, not displaying it
XML (eXtensible Markup Language) is a W3C standard for representing structured data as text. XML 1.0 became a W3C Recommendation on 10 February 1998 (its fifth edition dates from 2008). It is a simplified subset of SGML designed to be easy to parse and to work across platforms, programming languages and character sets (Unicode).
The key word is extensible: XML has no predefined tags. You invent element names that describe your data, so the document explains itself. XML does nothing on its own — it is a container; programs read it, validate it, query it and transform it.
XMLschemes.xml — the sample document used throughout this topic (valid against the DTD shown later)
Data exchange between systems — banks, governments, e-filing, SOAP web services (SOAP messages are XML; WSDL and UDDI are XML too).
Document formats — XHTML, SVG graphics, MathML, RSS/Atom feeds; DOCX and ODF files are zipped XML.
AJAX originally meant JavaScript fetching XML (the X in the name), although JSON now dominates.
Aspect
XML
HTML
Purpose
Describe, store and transport data
Display data in a browser
Tags
User-defined
Predefined (p, table, a…)
Case
Case-sensitive
Case-insensitive
Closing tags
Always required
Optional for some elements
Errors
Fatal — a parser must stop
Browsers recover silently
Attribute values
Must be quoted
Quotes optional for simple values
Whitespace
Preserved and passed to the application
Collapsed when displayed
02Well-formed XML: the syntax rules
An XML document may begin with a prolog: the XML declaration<?xml version="1.0" encoding="UTF-8" standalone="no"?> — which, if present, must be the very first thing in the file, with not even a space before it — then optional comments, processing instructions and a DOCTYPE. After the prolog comes exactly one root element containing everything else.
Rules of well-formedness
Exactly one root
All content sits inside a single top-level element; <a/><b/> as a whole document is an error.
Every element closed
Each start tag needs a matching end tag, or the element is self-closing: <photo src="p.jpg"/>.
Proper nesting
<b><i>…</i></b> is fine; <b><i>…</b></i> (overlap) is an error.
Case-sensitive names
<Name>…</name> does not match; District and district are different elements.
Quoted attribute values
Single or double quotes are both fine; id=s1 without quotes is an error. An element may not repeat an attribute.
Escape < and &
In text and attribute values write < and &. A raw > is allowed, except in the sequence ]]>.
Legal names
Names start with a letter or underscore (not a digit), contain no spaces, and may not begin with the letters xml in any case — those are reserved.
A document that obeys these rules is well-formed. It is valid if, in addition, it conforms to a DTD or schema. A non-validating parser checks only well-formedness; a validating parser also checks the grammar. Unlike browsers with HTML, an XML parser that meets a well-formedness error must report it and stop — there is no guessing.
PSC favourite
Which causes a well-formedness error? → unquoted attribute values, multiple root elements, overlapping tags, a case mismatch between start and end tags, a raw < or & in text. Comments and empty-element syntax <br/> are perfectly legal.
03Elements vs attributes, CDATA, entities and namespaces
Use an element when…
the value is real data the user cares about
it may repeat (several phone elements)
it has structure of its own (child elements)
it is long text, or its order matters
Use an attribute when…
it is metadata about the element — an id, a type, a unit
it occurs at most once per element
it is a short, simple value
attributes cannot contain elements and their order is not significant
XMLEntity references versus a CDATA section — both carry the same characters
<note><!-- a comment: not parsed as data; may not contain two hyphens in a row -->
<?audit level="high"?><!-- a processing instruction for some application --><formula>if (units < 50 && vacant) then reopen</formula><script><![CDATA[ if (units < 50 && vacant) { reopen(); } ]]></script><owner>Board & Co. © 2026</owner></note>
Entity
Character
Must escape?
<
<
Yes, always in text and attributes
&
&
Yes, always
>
>
Only in the sequence ]]>
"
"
Inside a double-quoted attribute value
'
'
Inside a single-quoted attribute value
XML's five predefined entities; any character can also be written as © (decimal) or © (hex)
A CDATA section, <![CDATA[ … ]]>, marks text the parser passes through without looking for markup — handy for code or formulas full of < and &. It cannot contain ]]> and cannot nest. A processing instruction<?target data?> passes an instruction to an application; the best known is <?xml-stylesheet type="text/xsl" href="schemes.xsl"?>, which tells a browser to transform the document with XSLT. (The XML declaration looks like one but is not a processing instruction.)
Namespaces (W3C, 1999) prevent name clashes when vocabularies are mixed — an HTML table and a furniture table in one document. A prefix is bound to a URI with xmlns:prefix="URI", and xmlns="URI" sets the default namespace for unprefixed elements. The URI is only a unique identifier; nothing is downloaded from it. Unprefixed attributes are in no namespace at all.
A DTD (inherited from SGML) is a grammar listing the elements and attributes a document may use. It can be internal, inside the document — <!DOCTYPE schemes [ … ]> — or external in a separate file: <!DOCTYPE schemes SYSTEM "schemes.dtd"> for a private file, or PUBLIC "formal public identifier" "URL" for a published standard such as XHTML.
XMLschemes.dtd — referenced by schemes.xml; a validating parser accepts the sample document
<!ELEMENT schemes (scheme+)>
<!ELEMENT scheme (name, district, units, contact?)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT district (#PCDATA)>
<!ELEMENT units (#PCDATA)>
<!ELEMENT contact (phone+ | email)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ATTLIST scheme
id ID #REQUIRED
type (rental | ownership) "ownership"
status CDATA #IMPLIED
board CDATA #FIXED "KSHB">
<!ENTITY kshb "Kerala State Housing Board">
Content model
Meaning
(#PCDATA)
Parsed character data — text only
EMPTY
No content at all, e.g. <!ELEMENT br EMPTY>
ANY
Any mix of declared elements and text (no checking)
(a, b, c)
Sequence: a then b then c, in that order
(a | b)
Choice: exactly one of a or b
a?
Optional: zero or one
a*
Zero or more
a+
One or more
no indicator
Exactly once
(#PCDATA | b | i)*
Mixed content: text freely mixed with b and i elements
So scheme must contain name, district and units in that order, optionally followed by one contact; a contact holds either one or more phone elements or exactly one email — not both.
<!ATTLIST> part
Options
Type
CDATA (any text) · ID (unique in the document, must be a valid XML name, at most one per element) · IDREF / IDREFS (refer to IDs) · NMTOKEN(S) · ENTITY · enumeration (rental | ownership)
Default
#REQUIRED (must be given) · #IMPLIED (optional, no default) · #FIXED "value" (always that value) · "value" (default used when omitted)
<!ENTITY kshb "Kerala State Housing Board"> declares an internal general entity: writing &kshb; in the document inserts the text. External entities pull in files (<!ENTITY terms SYSTEM "terms.xml">) and parameter entities (<!ENTITY % common "…">, used as %common;) are macros usable only inside the DTD.
Limits of DTDs
A DTD is not written in XML, has no data types (units could hold 'many'), cannot state '2 to 5 occurrences' directly (only through a clumsy nested model such as (a, a, (a, (a, a?)?)?)), and does not understand namespaces. XML Schema was created to fix exactly these gaps.
05XML Schema (XSD)
XML Schema (W3C Recommendation 2001; version 1.1 in 2012), also called XSD, describes the structure and data types of a document. A schema is itself an XML document in the namespace http://www.w3.org/2001/XMLSchema, conventionally with the prefix xs: or xsd:.
XMLschemes.xsd — an instance links to it with xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xsi:noNamespaceSchemaLocation="schemes.xsd"
Simple types hold only text (no child elements, no attributes); complex types may have child elements and/or attributes.
Compositors: xs:sequence (children in this order), xs:choice (exactly one of them), xs:all (each at most once, any order).
minOccurs and maxOccurs both default to 1; maxOccurs="unbounded" means no upper limit; minOccurs="0" makes an element optional.
Attributes: use="required", "optional" (the default) or "prohibited", plus default or fixed values.
Built-in types: xs:string, xs:boolean, xs:decimal, xs:integer, xs:int, xs:positiveInteger, xs:float, xs:double, xs:date (YYYY-MM-DD), xs:time, xs:dateTime, xs:anyURI, xs:ID, xs:IDREF. There is no xs:varchar — that is SQL.
Facets restrict a base type: minInclusive/maxInclusive, minExclusive/maxExclusive, length, minLength/maxLength, pattern (regular expression), enumeration, totalDigits, fractionDigits, whiteSpace.
Against this schema the validator rejects <units>0</units> (not a positive integer), <units>7000</units> (above maxInclusive), <district>kollam</district> (fails the pattern), <launched>15/08/2025</launched> (not an xs:date — it must be 2025-08-15) and a second district after units (breaks the sequence).
Aspect
DTD
XML Schema (XSD)
Syntax
Its own SGML-style syntax
Written in XML
Data types
Essentially text only (CDATA, #PCDATA)
40+ built-in types plus user-derived types
Namespaces
Not supported
Fully supported
Occurrence control
?, *, + only
Any minOccurs / maxOccurs
Restrictions
Enumerations for attributes only
Facets: ranges, lengths, patterns, enumerations
Reuse
Parameter entities
Named types, extension and restriction (inheritance)
Entities
Can declare entities
Cannot declare entities
Ease
Short and simple
Verbose but far more powerful
06Parsing XML: DOM, SAX and StAX
A parser reads XML text, checks it and hands its structure to a program. There are two classic styles. The DOM (Document Object Model, a W3C standard) parser reads the whole document and builds a tree of node objects in memory — document, elements, attributes, text — which the program can walk in any direction, search and modify, then write back out.
JavaScriptDOM parsing in the browser — paste it into the Web playground tool on this page
const text = `<schemes>
<scheme id="s1"><name>Sneha Nagar</name><units>120</units></scheme>
<scheme id="s2"><name>Kayal View Flats</name><units>64</units></scheme>
</schemes>`;
const doc = new DOMParser().parseFromString(text, "application/xml");
if (doc.getElementsByTagName("parsererror").length > 0) {
console.log("Not well-formed!");
}
const schemes = doc.getElementsByTagName("scheme"); // both scheme nodes
for (const s of schemes) {
console.log(s.getAttribute("id"), s.querySelector("name").textContent);
}
schemes[1].querySelector("units").textContent = "70"; // edit the tree in memory
console.log(new XMLSerializer().serializeToString(doc)); // write it back out
SAX (Simple API for XML, created by David Megginson and the xml-dev mailing list in 1998) never builds a tree. It reads the document from start to end and fires events — startDocument, startElement, characters, endElement, endDocument — into callback methods that you write. It is a push parser: the parser drives, your handler reacts.
JavaA SAX handler that totals the units while streaming — it never holds more than one element's text
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import java.io.File;
public class UnitCounter extends DefaultHandler {
private final StringBuilder text = new StringBuilder();
private int total = 0;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) {
text.setLength(0); // start collecting fresh text
if (qName.equals("scheme")) {
System.out.println("Scheme " + atts.getValue("id"));
}
}
@Override
public void characters(char[] ch, int start, int length) {
text.append(ch, start, length); // may be called several times per element
}
@Override
public void endElement(String uri, String localName, String qName) {
if (qName.equals("units")) {
total += Integer.parseInt(text.toString().trim());
}
}
@Override
public void endDocument() {
System.out.println("Total units = " + total); // 232 for schemes.xml
}
public static void main(String[] args) throws Exception {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new File("schemes.xml"), new UnitCounter());
}
}
Java org.xml.sax (SAXParser, DefaultHandler); .NET's nearest equivalent, XmlReader, is a forward-only pull parser (like StAX)
StAX (Streaming API for XML, Java JSR 173) is a pull parser: like SAX it streams and uses little memory, but the program asks for the next event when it is ready (reader.hasNext(), reader.next()), which makes code easier to structure; StAX can also write XML. PHP's SimpleXML (simplexml_load_file) is a convenient tree API for small documents.
PSC favourite
Event-driven, callbacks, low memory, cannot modify → SAX. Tree in memory, random access, can modify → DOM. The HTML page a browser builds is also a DOM tree — the same model JavaScript manipulates.
07XPath and XSLT
XPath (W3C, 1999) is a small expression language for selecting nodes in an XML tree, written like file-system paths. It is used inside XSLT, XQuery, XML Schema, Java's javax.xml.xpath, and even browser testing tools. Results on schemes.xml:
XPath expression
Selects / returns
/schemes/scheme
All 3 scheme elements (absolute path from the root)
//name
Every name element at any depth (3 nodes)
/schemes/scheme[2]/name
Kayal View Flats — positions are counted from 1
//scheme[last()]/@id
s3 — the id attribute of the last scheme
//scheme[@type='rental']/name
Sneha Nagar
//scheme[units > 50]/name
Sneha Nagar and Kayal View Flats
//scheme[not(contact)]/name
Thanal Homes
count(//phone)
2
sum(//units)
232
//contact/..
The parents of contact elements — schemes s1 and s2
//scheme/*
Every child element of every scheme (* = any element)
XSLT (eXtensible Stylesheet Language Transformations, W3C 1999; versions 2.0 in 2007 and 3.0 in 2017) is a template language that transforms an XML document into another XML document, HTML or plain text. A stylesheet is a set of templates; each xsl:template match="…" says what to output when the processor meets matching nodes.
XMLschemes.xsl — produces a table sorted 120, 64, 48 and the line 'Total units: 232'
xsl:value-of select="…" — output the text value of an XPath expression.
xsl:for-each — loop over nodes; xsl:sort inside it orders them (data-type="number" for numeric order).
xsl:if test="…" — one condition (no else); xsl:choose / xsl:when / xsl:otherwise — if-else chains.
xsl:apply-templates — let matching templates process child nodes (rule-based style).
Attach a stylesheet to a document with <?xml-stylesheet type="text/xsl" href="schemes.xsl"?>; or run it on a server (Java Transformer, PHP XSLTProcessor, xsltproc).
08XML vs JSON vs HTML
JSON (JavaScript Object Notation), popularised by Douglas Crockford in the early 2000s and standardised as RFC 8259 and ECMA-404, writes the same data as nested objects { } and arrays [ ] of name/value pairs separated by commas. Here is scheme s1 as JSON:
Rule of thumb: JSON for lightweight data between programs (REST, AJAX); XML when you need schemas with types, namespaces, mixed text-and-markup documents, digital signatures, or standards that already use it (SOAP, SVG, office formats).
Step through · SAX parsing schemes.xml — events pushed to a handler
step 1 / 9
Step 1: parse(file, handler)
The program creates a SAXParser and hands it the file and a handler object. From here on the parser is in control (push model).
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Finding every well-formedness error
List every error in this document and fix it: line 1 <?xml version="1.0"?>, then <Applicants>, <applicant id=A101>, <name>Anil & Sons</name>, <income>< 300000</income>, <district>Kollam</District>, </applicant>, <applicant id="A102"><name>Meera</applicant></name>, </applicants>, and finally <note>Draft</note> after the closing root tag.
EX 2Checking documents against a DTD
Using schemes.dtd, decide whether each scheme is valid: (a) name, district, units only; (b) name, district, units, units; (c) a contact holding one phone and one email; (d) id="s2" used on two schemes; (e) type="lease"; (f) id="1".
A nightly job must total the 'amount' field in a 2 GB XML export of property-tax receipts on a server with 4 GB of RAM. A separate admin tool edits a 40 KB configuration file. Assuming a DOM tree takes about 5 times the file size in memory, which parser suits each job?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write a DTD for a library document in which library holds one or more book elements; each book has a title, one or more author elements and an optional year; every book has a required unique isbn attribute and an optional lang attribute that defaults to en.
Q2
Write XSD declarations for (a) an element pincode holding exactly six digits whose first digit is not 0, and (b) an element phone that may appear from 1 to 3 times inside a sequence.
Q3
Predict the output of this XSLT on schemes.xml: a template matching / that writes <ul>, then xsl:for-each select="schemes/scheme" containing <xsl:sort select="name"/> and <xsl:if test="units > 50">, which outputs <li> + the name + ' (' + the @id + ')'; then </ul> and <p>Schemes: + count(schemes/scheme) + </p>.
Q4
In the namespaced order document shown in the namespaces section, give the namespace URI of: order, f:table, f:legs, h:td, note, and the attribute material.
Q5
Convert the scheme s2 element from schemes.xml into JSON, and state two pieces of information that are harder to keep in JSON than in XML.
Exam traps
Well-formed ≠ valid: a document can be perfectly well-formed yet violate its DTD. Validity always implies well-formedness.
XML is case-sensitive — <Name> and <name> are different elements — unlike HTML.
XPath positions start at 1: scheme[1] is the first scheme, not the second.
#IMPLIED means optional with no default, not 'implied value'; #FIXED attributes can be omitted but cannot take another value.
A raw > is legal in XML text; only < and & must always be escaped (and ]]> must not appear).
XSL is a family: XSLT transforms, XPath selects, XSL-FO formats pages. 'XSL' in a question often means XSLT.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
XML, DTD, XML Schema & parsing · Question 1 of 12✓ 0 · ✗ 0
XML was primarily designed to:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 4✓ 0 · ✗ 0
Modelled on QP 105/2024 · Higher Secondary School Teacher (Junior) Computer Science (8 Aug 2024), Q.83 (reworded)original paper (PDF)
Which of these is not a valid XML (XML Schema) data type?