Represent structured data with elements, attributes and explicit document rules.

Before starting: Plain-text files, nesting, and basic data structures.

Practice project: Validate an order document and distinguish syntax, schema, and business errors.

1. XML Basics & Document Architecture

  1. XML Introduction, W3C Standards & Data Architecture
  2. XML Document Architecture & Prolog Declaration Rules
    Read the example and try it

    Place the optional declaration at the beginning and keep one outer element. The declared encoding must match the saved bytes.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <?xml version="1.0" encoding="UTF-8"?>
    <board><room>Lake</room></board>

    Compare a declaration at the start with one after a newline.

    Parse <?xml version="1.0"?><room/> and then the same text with a newline before the declaration.

    Expected result
    First parses. Second raises a syntax error because the declaration is no longer at the start. Exact error wording depends on the parser.
  3. XML Syntax Rules, Tags & Well-Formedness Criteria
    Read the example and try it

    Close the innermost element first. Both stop elements below are siblings inside one route.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <route><stop>Hill</stop><stop>Park</stop></route>

    Find and repair a mismatched tag in a two-element document.

    Start with <rooms><room></Room></rooms>.

    Expected result
    The original fails. Changing </Room> to </room> produces a well-formed tree with one child named room.
  4. XML Elements, Naming Conventions & Tree Hierarchy
    Read the example and try it

    Read the path from the outside in. Gate 3 belongs to East because its element is inside that station.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <network><station name="East"><gate>3</gate></station></network>

    Wrap two sibling records in a single container.

    Start with <room/><room/> as a document.

    Expected result
    It fails with multiple root elements. <rooms><room/><room/></rooms> parses with root rooms and two children.
  5. XML Attributes vs Child Elements: Enterprise Design Patterns
    Read the example and try it

    Use a short attribute for an identifier and repeating children for an ordered list. This route can gain another stop without changing its attribute names.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <route id="R7"><stop>Hill</stop><stop>Lake</stop></route>

    Represent a contact with two phone numbers and one ID.

    Represent contact ID A and numbers 101 and 202.

    Expected result
    <contact id="A"><phone>101</phone><phone>202</phone></contact> has one id attribute and two phone children in order.

2. XML Data Types, Entities & Namespaces

  1. XML Character Entities & Predefined Escape Sequences
    Read the example and try it

    An ampersand starts a reference in XML text. Escape it so the parsed label contains a literal ampersand.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <stop>Park &amp; Ride</stop>

    Encode a room name containing an ampersand and read its text value.

    Encode room name R&D inside name.

    Expected result
    <name>R&amp;D</name> parses to the text R&D. A bare & in that position is malformed.
  2. XML CDATA Sections: Handling Raw Unparsed Character Blocks
    Read the example and try it

    CDATA lets a document carry characters that resemble markup. The parser still supplies ordinary text to the application.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <example><![CDATA[if (seats < 3) showWarning();]]></example>

    Store a short markup sample as text and compare the parsed result.

    Use <sample><![CDATA[<room/>]]></sample>.

    Expected result
    The sample's text is literally <room/>. There is no room child.
  3. XML Namespaces (xmlns), Prefixes & Scope Resolution
    Read the example and try it

    The prefix is a short local name for a namespace URI. Two elements called name can belong to different vocabularies.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <record xmlns:r="urn:study:rooms" xmlns:p="urn:study:pupils"><r:name>Hall</r:name><p:name>Mira</p:name></record>

    Use two different prefixes bound to the same namespace.

    Bind prefixes a and b to urn:campus in two documents, each containing a room root.

    Expected result
    Both expanded names are {urn:campus}room. Prefix spelling differs but a namespace-aware lookup treats the names as equal.
  4. XML Character Encodings (UTF-8, UTF-16, ISO) & BOM Pitfalls
    Read the example and try it

    Save this document as UTF-8 before parsing it. A declaration describes the encoding and cannot repair bytes saved in another encoding.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <?xml version="1.0" encoding="UTF-8"?>
    <destination>São Bento</destination>

    Compare UTF-8 bytes for an accented name with the declared encoding.

    Encode Café as UTF-8 bytes and declare UTF-8. Inspect the bytes for é.

    Expected result
    Hex C3 A9 represents é. The parsed text is Café. Mislabeling those bytes as Latin-1 can produce Café instead of the intended text.
  5. XML Comments, Whitespace Preservation & Processing Instructions
    Read the example and try it

    A comment can give the editor context without becoming an element. Preserve spaces deliberately in text whose layout matters.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <sign xml:space="preserve"><!-- Two columns on the sign -->A4   East</sign>

    Repair a comment containing a forbidden double hyphen.

    Change <!--north--room--> to a valid comment in <rooms/>.

    Expected result
    For example <!--north-room--><rooms/> parses. The original double hyphen inside comment text is forbidden.

3. Document Type Definition (DTD) Validation

  1. XML DTD Architecture: Internal vs External DTD Validation
    Read the example and try it

    An internal DTD defines the expected children in the document itself. A validating parser checks the declarations against the root and its contents.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <!DOCTYPE route [<!ELEMENT route (stop+)><!ELEMENT stop (#PCDATA)>]>
    <route><stop>Lake</stop></route>

    Declare a small catalog with a required child.

    Declare catalog (item+) and item EMPTY. Compare <catalog><item/></catalog> with <catalog/>.

    Expected result
    First validates. The empty catalog is well-formed but fails the required-child constraint.
  2. DTD Element Declarations & Quantifiers (?, *, +, |, ,)
    Read the example and try it

    A comma in a DTD content model specifies an order. The plus means the route needs at least one stop after its name.

    DTD declarations for a route document.

    <!ELEMENT route (name, stop+)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT stop (#PCDATA)>

    Test a title then price against the reverse order.

    Declare item (title,price) with title and price as text children.

    Expected result
    title followed by price validates. Reversing those same children fails validation.
  3. DTD Attribute List Declarations (#REQUIRED, #IMPLIED, #FIXED, CDATA)
    Read the example and try it

    Use an attribute declaration to make a code mandatory. An element may be empty and still need its identifying attribute.

    DTD declarations for an empty gate element.

    <!ELEMENT gate EMPTY>
    <!ATTLIST gate code ID #REQUIRED>

    Validate two records differing only in presence of the required ID.

    Declare room EMPTY with id ID #REQUIRED. Test <room id="A"/> and <room/>.

    Expected result
    The first validates; the second fails DTD validation because the attribute is missing.
  4. DTD Entities: General, Parameter, Internal & External Subsets
    Read the example and try it

    An internal entity expands to its declared text in a trusted document. Keep external entity resolution disabled for untrusted input.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <!DOCTYPE notice [<!ELEMENT notice (#PCDATA)><!ENTITY hall "East Hall">]>
    <notice>Meet at &hall;.</notice>

    Use an internal entity for a short shared label.

    Declare the internal entity campus as North, and set <label>&campus;</label>.

    Expected result
    With internal entity expansion enabled for this trusted local fixture, the resulting text is North. No external resource is required.
  5. XML Validation against DTD: Well-Formed vs Valid Documents
    Read the example and try it

    Balanced tags make this document well formed. Validation fails because the route declaration requires a stop child.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <!DOCTYPE route [<!ELEMENT route (stop)><!ELEMENT stop (#PCDATA)>]>
    <route/>

    Build a balanced document with a child missing from the declared model.

    Declare rooms (room+) and submit <rooms/>.

    Expected result
    Basic parsing succeeds. DTD validation fails because rooms contains zero room elements.

4. XML Schema Definition (XSD) Foundations

  1. XML Schema (XSD) Introduction & Architectural Superiority over DTD
    Read the example and try it

    Use an XSD type when text must represent a particular value. A negative seat count fails this type's value restriction.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="seats" type="xs:nonNegativeInteger"/></xs:schema>

    Validate a nonnumeric string against an integer element.

    Define seats globally as xs:integer. Validate <seats>8</seats> and <seats>eight</seats>.

    Expected result
    8 validates. The text eight fails integer validation although both documents parse.
  2. XSD Schema Declaration, targetNamespace & elementFormDefault
    Read the example and try it

    A global element belongs to the schema's target namespace. An instance must use that URI to match this declaration.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:study:rooms" elementFormDefault="qualified"><xs:element name="room" type="xs:string"/></xs:schema>

    Validate two documents that use different prefixes for the same namespace.

    Declare a global room in target namespace urn:campus. Bind prefixes a and b to that URI in separate root elements.

    Expected result
    Both instances validate against the same global declaration. An unqualified room root fails.
  3. XSD Simple Types & Built-in Scalar Types (string, integer, date)
    Read the example and try it

    A date field can enforce a date-shaped value. Place this element declaration inside an XSD schema using the xs prefix.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:element name="travelDay" type="xs:date"/>

    Restrict a code to a short set of text values.

    Restrict roomCode to enumeration Lab and Hall. Test Lab and Gym.

    Expected result
    Lab validates; Gym fails the enumeration restriction.
  4. XSD Complex Types & Compositors (xs:sequence, xs:all, xs:choice)
    Read the example and try it

    A sequence requires the children in the given order. The schema fragment below expects a name followed by a seat count.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:complexType name="Room"><xs:sequence><xs:element name="label" type="xs:string"/><xs:element name="seats" type="xs:int"/></xs:sequence></xs:complexType>

    Validate two child orders against a sequence.

    Use a sequence with required name then seats.

    Expected result
    <room><name>Lab</name><seats>8</seats></room> validates. Putting seats before name fails.
  5. XSD Facets, Patterns (RegEx) & Enumeration Restrictions
    Read the example and try it

    Restrict a string to the ticket classes the application understands. A spelling outside the list fails validation.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:simpleType name="Fare"><xs:restriction base="xs:string"><xs:enumeration value="adult"/><xs:enumeration value="child"/></xs:restriction></xs:simpleType>

    Restrict a seat count to the range 1 through 20.

    Use an integer restriction with minInclusive=1 and maxInclusive=20. Test 0,1,20,21.

    Expected result
    Invalid, valid, valid, invalid; both endpoints are included.

5. Advanced XML Schema & Validation

  1. XSD Attribute Groups, Mixed Content & Nillable (xsi:nil) Elements
    Read the example and try it

    A nilled element can signal a known field with no current value. Its schema declaration must permit nil and its instance content must be empty.

    XML instance fragment for a nillable arrival element.

    <arrival xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

    Model a sentence with an emphasized child word.

    Use a mixed paragraph type permitting an em child. Parse <p>Read <em>this</em> first.</p>.

    Expected result
    The mixed text and child can validate. Reading text in document order gives Read this first.
  2. XSD Occurrence Indicators: minOccurs, maxOccurs & unbounded Arrays
    Read the example and try it

    Occurrence limits apply to each element particle in a schema. This declaration lets a route omit notes or provide up to two.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:element name="note" type="xs:string" minOccurs="0" maxOccurs="2"/>

    Test zero, one and two occurrences against a chosen maximum.

    Set minOccurs=0 and maxOccurs=1 for a note child.

    Expected result
    Zero notes: valid. One note: valid. Two notes: invalid.
  3. XSD Schema Inclusion & Import: xs:include vs xs:import
    Read the example and try it

    Import a separate vocabulary by namespace. Use include when combining compatible schema documents for the same namespace.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:import namespace="urn:study:fares" schemaLocation="fares.xsd"/>

    Separate shared same-namespace types from imported types.

    Place same-namespace common types in common.xsd and types for urn:other in other.xsd.

    Expected result
    Use xs:include for compatible same-namespace common.xsd and xs:import namespace="urn:other" for the other schema. Relative schema locations resolve against the containing schema.
  4. XSD Schema Validation in Production Pipelines & CI/CD
    Read the example and try it

    Check a fixture against its schema before accepting it. This command requires xmllint and the two named local files.

    Terminal with xmllint installed and the two named files available.

    xmllint --nonet --noout --schema room.xsd room.xml

    Parse a well-formed document and then test a type mismatch against its schema.

    Parse <seats>none</seats>, then validate against a schema specifying xs:integer.

    Expected result
    Parsing passes because markup is balanced. Validation fails at seats because none is not an integer.
  5. XML Schema Annotations: xs:annotation, xs:documentation & xs:appinfo
    Read the example and try it

    Place the unit beside the schema rule so someone reading the contract can interpret the number correctly.

    XSD schema or declaration. Place fragments in an xs:schema element defining xmlns:xs="http://www.w3.org/2001/XMLSchema".

    <xs:element name="duration" type="xs:positiveInteger"><xs:annotation><xs:documentation>Journey time in whole minutes.</xs:documentation></xs:annotation></xs:element>

    Add a human-readable note explaining the units of a numeric field.

    Add xs:documentation saying "Minutes since opening" to an xs:integer field.

    Expected result
    A reader sees the unit in the schema. Both before and after the annotation, an integer validates and a noninteger fails.

6. XPath & Navigating XML Trees

  1. XPath Fundamentals, Data Model & Node Classifications
    Read the example and try it

    Start from a tiny tree and identify what the result should contain. The attribute is a different node from the stop's text.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <route><stop id="S4">Lake</stop></route>
    <!-- XPath /route/stop/@id selects S4; /route/stop/text() selects Lake. -->

    Select a catalog's direct item elements from the document root.

    Use <catalog><item id="A"/><group><item id="B"/></group></catalog>.

    Expected result
    /catalog/item selects only A. The nested item B is not a direct child.
  2. XPath Syntax, Location Paths & Step Navigation (/, //, ., .., @)
    Read the example and try it

    A single slash follows a direct child step. This expression selects only names on stops directly inside the route.

    XPath expression. Evaluate against a route document containing stop elements with the named attributes.

    /route/stop/@name

    Select an item's ID and its name child separately.

    Use <item id="A"><name>Lab</name></item>.

    Expected result
    string(/item/@id) gives A; string(/item/name) gives Lab.
  3. XPath Predicates & Filtering Expressions ([price > 50], position())
    Read the example and try it

    A predicate narrows a selected node set. The numeric comparison below keeps stops with an expected wait over five minutes.

    XPath expression. Evaluate against a route document containing stop elements with the named attributes.

    /route/stop[@wait > 5]

    Compare item[1] within two separate groups.

    Group 1 has items A,B. Group 2 has C,D. Use /catalog/group/item[1].

    Expected result
    A and C. In contrast, (/catalog/group/item)[1] gives A only.
  4. XPath Axes & Tree Traversal (ancestor, descendant, sibling, parent)
    Read the example and try it

    Navigate from the current stop to its next stop sibling. The immediate match has position one on this forward axis.

    XPath expression. Evaluate against a route document containing stop elements with the named attributes.

    following-sibling::stop[1]

    Navigate from a price to its item and then to a sibling field.

    Use <item><name>Lab</name><price>8</price></item>. Start at price and evaluate ../name.

    Expected result
    One name element is selected and its text is Lab.
  5. XPath Built-in Functions & Numeric / String Operators (count, contains)
    Read the example and try it

    Count the matching stop elements rather than counting all children, which could include names and notes.

    XPath expression. Evaluate against a route document containing stop elements with the named attributes.

    count(/route/stop[@accessible='yes'])

    Count available items and separately sum their prices.

    Use available items with prices 2 and 5 plus an unavailable item priced 9.

    Expected result
    Count of available items=2; sum of their prices=7. Include the availability predicate in both expressions.

7. XSL & XSLT Transformations

  1. XSL & XSLT Overview: Architecture, Pipeline & Stylesheet Skeleton
    Read the example and try it

    An XSLT transform walks an input tree and builds an output. This complete stylesheet turns a stop count into plain text.

    Complete XSLT 1.0 stylesheet. Supply a route document with stop children.

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/><xsl:template match="/"><xsl:value-of select="count(/route/stop)"/></xsl:template></xsl:stylesheet>

    Trace a catalog and a stylesheet into an HTML list.

    Transform a catalog with two names Lab and Hall into an HTML ul with an li per name.

    Expected result
    Two li elements appear in source order under ul: Lab then Hall. Serializer whitespace can vary.
  2. XSLT Templates (<xsl:template match>) & Value Extraction (<xsl:value-of>)
    Read the example and try it

    In an XSLT template the matched node becomes the context. Reading @name here means the current stop's name.

    XSLT fragment. Place inside a stylesheet with the xsl namespace declared. Loop and conditional fragments belong inside a template.

    <xsl:template match="stop"><li><xsl:value-of select="@name"/></li></xsl:template>

    Compare outputting a name's value with copying its element.

    Given <name><b>Lab</b></name>, apply value-of to name, then copy-of to name in a second transform.

    Expected result
    value-of emits the text Lab. copy-of preserves the name element and its nested b element.
  3. XSLT Iteration (<xsl:for-each>) & Dynamic Sorting (<xsl:sort>)
    Read the example and try it

    Place sort first in the loop. Numeric ordering puts minute 9 before minute 12 when comparing the attributes as numbers.

    XSLT fragment. Place inside a stylesheet with the xsl namespace declared. Loop and conditional fragments belong inside a template.

    <xsl:for-each select="stop"><xsl:sort select="@minute" data-type="number"/><li><xsl:value-of select="@name"/></li></xsl:for-each>

    Sort items by numeric price and compare with text sorting.

    Sort prices shown as strings "10","2","30".

    Expected result
    Numeric ascending order is 2,10,30. Text ascending order is 10,2,30 for these digits.
  4. XSLT Conditional Logic: xsl:if and xsl:choose / when / otherwise
    Read the example and try it

    Choose one result for the current stop. An otherwise branch ensures on-time stops receive a label too.

    XSLT fragment. Place inside a stylesheet with the xsl namespace declared. Loop and conditional fragments belong inside a template.

    <xsl:choose><xsl:when test="@late='yes'">Delayed</xsl:when><xsl:otherwise>On time</xsl:otherwise></xsl:choose>

    Label prices as low, medium or high with an otherwise branch.

    Use thresholds price <5 → low, price <10 → medium, otherwise high. Test 3,7,10.

    Expected result
    low, medium, high. The price 10 belongs in otherwise.
  5. XSLT Client-Side Browser Rendering vs Server-Side Transformation (PHP XSLTProcessor)
    Read the example and try it

    A server can transform trusted XML and XSL files before sending the result. Check the returned value before publishing it.

    PHP script fragment with DOM and XSL extensions and trusted local input files.

    $input = new DOMDocument(); $input->load("route.xml");
    $style = new DOMDocument(); $style->load("route.xsl");
    $processor = new XSLTProcessor(); $processor->importStylesheet($style);
    $body = $processor->transformToXML($input);
    if ($body !== false) { echo $body; }

    Outline a transformation using trusted local inputs and controlled resource access.

    Use a local trusted stylesheet and a small in-memory source. Disable external file and network access in the transform.

    Expected result
    An ordinary in-memory transform succeeds. A stylesheet attempting a prohibited external read must fail closed without disclosing file contents.

8. XML Parsers: DOM, SAX, StAX & Browser JavaScript

  1. XML Parsers Architecture: DOM vs SAX vs StAX Model Comparison
    Read the example and try it

    A streaming reader can release completed elements instead of retaining their text and attributes. This small Python example counts stop end events.

    Python 3 with the standard library.

    import io, xml.etree.ElementTree as ET
    stream = io.BytesIO(b"<route><stop/><stop/></route>")
    count = 0
    for _, node in ET.iterparse(stream, events=("end",)):
        if node.tag == "stop": count += 1
        node.clear()
    print(count)

    Choose a tree or a stream for random access and sequential reading.

    Choose between random access to sibling records and scanning a very large file for one identifier.

    Expected result
    A DOM tree supports repeated navigation. A streaming reader can scan until the identifier with bounded memory if processed records are released.
  2. XML DOM in Browser JavaScript: DOMParser, XMLSerializer & Traversal
    Read the example and try it

    A browser parser returns a document. Look for a parser error before navigating to the first stop.

    Browser JavaScript console.

    const doc = new DOMParser().parseFromString('<route><stop>Hill</stop></route>', 'application/xml');
    if (!doc.querySelector('parsererror')) console.log(doc.querySelector('stop').textContent);

    Parse balanced and mismatched tags and compare the documents.

    Use browser DOMParser on <room/> and <room></rooms>.

    Expected result
    The first document has a room root. The second has a parser-error document or element; test for an error before using it.
  3. Fetching XML via AJAX & Fetch API (responseXML) for Dynamic SPAs
    Read the example and try it

    An HTTP success and valid XML are separate checks. Test both before passing the document to the board.

    Browser JavaScript. Call the function with a same-origin XML URL.

    async function loadRoute(url) {
      const res = await fetch(url); if (!res.ok) throw Error('Request failed');
      const doc = new DOMParser().parseFromString(await res.text(), 'application/xml');
      if (doc.querySelector('parsererror')) throw Error('Invalid XML');
      return doc;
    }

    Handle HTTP failure separately from malformed XML.

    Try three local responses: 404, HTTP 200 with <room/>, HTTP 200 with broken <room>.

    Expected result
    Report HTTP failure, success with root room, and XML parse failure respectively. Do not treat all three as successful XML data.
  4. SAX Event-Driven Parsing: Handlers, Callbacks & Big Data Pipelines
    Read the example and try it

    A SAX handler receives a callback for each opening tag. A simple counter needs no text buffer or complete in-memory tree.

    Python 3 with the standard library.

    from xml.sax import parseString, ContentHandler
    class Stops(ContentHandler):
        def __init__(self): super().__init__(); self.total = 0
        def startElement(self, name, attrs):
            if name == "stop": self.total += 1
    h = Stops(); parseString("<route><stop/><stop/></route>", h); print(h.total)

    Trace text split into two callbacks before an end-element event.

    Simulate characters("La"), characters("b"), then the end of name.

    Expected result
    The accumulated value is Lab. Replacing the buffer on every callback would incorrectly return just b.
  5. StAX (Streaming API for XML) & Pull-Parsing Models
    Read the example and try it

    A StAX reader advances only when the caller asks. Inspect attributes while positioned on the opening element.

    Java method fragment with an XMLStreamReader named reader.

    while (reader.hasNext()) {
        int event = reader.next();
        if (event == javax.xml.stream.XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("stop"))
            System.out.println(reader.getAttributeValue(null, "id"));
    }

    Stop reading after reaching a chosen record.

    Stream records A,B,C. Stop when the record with ID B is reached.

    Expected result
    The application reports B and stops its loop before processing C. A parser may have buffered input bytes beyond B internally.

9. Backend XML Processing (PHP, Python, Java)

  1. XML in PHP: Fast Object Access with SimpleXML (simplexml_load_string)
    Read the example and try it

    SimpleXML can read a small trusted document with property access. Cast an element to string when you need its text.

    PHP script fragment with SimpleXML enabled.

    $route = simplexml_load_string("<route><stop>Hill</stop></route>");
    if ($route !== false) { echo (string) $route->stop; }

    Extract one attribute and one child as separate strings.

    Use <room id="A"><name>Lab</name></room> with PHP SimpleXML.

    Expected result
    A Lab
  2. XML in PHP: Full DOM Tree Manipulation with DOMDocument
    Read the example and try it

    Build a text node for an input value. Serialising the document then escapes markup characters correctly.

    PHP script fragment with the DOM extension.

    $doc = new DOMDocument();
    $stop = $doc->appendChild($doc->createElement("stop"));
    $stop->appendChild($doc->createTextNode("Park & Ride"));
    echo $doc->saveXML($stop);

    Append a name containing an ampersand and serialize the document.

    Append the string R&D through DOMDocument::createTextNode under name.

    Expected result
    Serialized element: <name>R&amp;D</name>. Reading its text returns R&D.
  3. XML in PHP: High Performance Streaming with XMLReader & XMLWriter
    Read the example and try it

    XMLReader can visit a small record without materialising its neighbours. Make sure you match the opening element rather than its closing event.

    PHP script fragment with XMLReader enabled.

    $r = new XMLReader();
    $r->XML('<route><stop id="S4"/></route>');
    while ($r->read()) {
        if ($r->nodeType === XMLReader::ELEMENT && $r->name === "stop") echo $r->getAttribute("id");
    }
    $r->close();

    Copy selected records one at a time into a new document.

    Read <rooms><room id="A"/><room id="B"/></rooms>. Write only room B under a fresh rooms root.

    Expected result
    The new document has one room child with id B. A self-closing child and an equivalent explicit end tag are both valid outputs.
  4. XML in Python: ElementTree (xml.etree.ElementTree) Mastery
    Read the example and try it

    ElementTree finds direct children with findall. Read each attribute while preserving input order.

    Python 3 with the standard library.

    import xml.etree.ElementTree as ET
    route = ET.fromstring('<route><stop id="H"/><stop id="L"/></route>')
    print([s.get("id") for s in route.findall("stop")])

    Check a missing optional child before reading its text.

    Parse <room><name>Lab</name></room> in ElementTree and look for note.

    Expected result
    find("note") returns None. Guard with is None before reading .text. An empty existing <note/> is a different case.
  5. XML in Java: JAXB (Jakarta XML Binding) & Enterprise DOM Architecture
    Read the example and try it

    A binding annotation maps an XML root to a Java type. This example needs Jakarta XML Binding and an implementation on the classpath.

    Java source in Stop.java with Jakarta XML Binding configured.

    @jakarta.xml.bind.annotation.XmlRootElement(name="stop")
    public class Stop {
        @jakarta.xml.bind.annotation.XmlAttribute
        public String id;
    }

    Compare binding a known document model with traversing DOM nodes.

    Map <room><name>Lab</name></room> to a Java Room with a name property, then traverse the same document using DOM.

    Expected result
    Both produce Lab. JAXB populates the bound model when a compatible JAXB runtime and mapping are installed; DOM requires explicit element navigation.

10. XML Web Services, Security & Enterprise Standards

  1. XML Web Services, SOAP Protocol & WSDL Contract Architecture
    Read the example and try it

    A SOAP envelope wraps an operation and its parameters. The service contract specifies the actual names, types and endpoint.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:r="urn:study:rooms"><s:Body><r:GetRoom><r:id>7</r:id></r:GetRoom></s:Body></s:Envelope>

    Locate an operation description before sketching a SOAP request.

    A WSDL operation is called GetRoom, its input element is GetRoomRequest in urn:rooms, and it accepts ID 7.

    Expected result
    The SOAP Body contains a namespace-qualified GetRoomRequest carrying 7 according to the declared schema. Use the WSDL binding for endpoint, envelope version and action.
  2. RSS 2.0 & Atom Web Feeds: XML Content Syndication Architecture
    Read the example and try it

    Give a feed entry a stable identifier so a reader can recognise an update. This RSS item fragment uses a local ID rather than a page address.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <item><title>New room exercise</title><guid isPermaLink="false">study-room-7</guid><description>Practise matching seat IDs.</description></item>

    Edit an entry title while preserving its identity.

    Keep Atom id urn:campus:notice:17 while changing title from Old hours to New hours.

    Expected result
    One logical entry is updated; readers should see the same ID and the new title, not two distinct entries.
  3. XML Security: XXE (XML External Entity Injection) Attacks & Prevention
    Read the example and try it

    Reject DTDs when an upload format has no need for them. This Python example uses defusedxml and explicitly forbids DTD declarations.

    Python 3 with defusedxml installed.

    from defusedxml.ElementTree import fromstring
    root = fromstring("<room><seats>4</seats></room>", forbid_dtd=True)
    print(root.findtext("seats"))

    Design a parser test that rejects external resource access.

    Use a local test-only sentinel entity and configure a parser to reject DOCTYPE or disable external substitution and access.

    Expected result
    The parse is rejected or the entity remains unresolved according to the chosen policy. Sentinel file contents must never appear in the result. No external network request is needed.
  4. XML Denial of Service: Billion Laughs Attack & Entity Expansion Defense
    Read the example and try it

    Test the rejection path with one small internal entity. There is no need to build an expanding attack fixture to check this parser setting.

    Python 3 with defusedxml installed.

    from defusedxml.ElementTree import fromstring
    from defusedxml.common import DefusedXmlException
    try:
        fromstring('<!DOCTYPE n [<!ENTITY a "x">]><n>&a;</n>', forbid_dtd=True)
    except DefusedXmlException:
        print("Rejected declaration")

    Specify resource limits and test with a small safe fixture.

    Use a small trusted internal expansion such as two copies of ab and an intentionally low application input-size cap.

    Expected result
    Permitted small expansion yields abab. Input exceeding the chosen cap is rejected before parsing. Separately disable unneeded entity expansion or enforce parser expansion limits; an input-size cap alone is insufficient.
  5. XML vs JSON & Modern Serialization: Enterprise Interview & Production Master Guide
    Read the example and try it

    Mixed content keeps text on both sides of an inline element. A converter needs an explicit representation to keep that order in JSON.

    XML document or fragment. Preserve case, nesting and namespace declarations when entering the example.

    <notice>Use <strong>Gate 4</strong> after noon.</notice>

    Represent a sentence with inline emphasis and compare the structure needed in JSON.

    Use <p>Read <em>this</em> first.</p>. Preserve ordering in a JSON representation.

    Expected result
    One equivalent representation is {"p":["Read ",{"em":"this"}," first."]}. Keep both spaces. A flat object with one text field cannot by itself preserve both text positions.

Separate well-formed XML from valid application data

A parser first checks XML syntax. A schema can then check structural rules and data types. Your application may still need business rules that neither syntax nor the schema expresses. The example below is well-formed, but a quantity of minus two can be invalid for an order. For untrusted XML, use hardened parser settings and avoid external entity resolution.

XML syntax example; use a schema validator or application checks for additional rules

<?xml version="1.0" encoding="UTF-8"?>
<order>
  <item code="BOOK-1">
    <quantity>-2</quantity>
  </item>
</order>
Check the output
A normal XML syntax parser accepts this well-formed document. An application rule requiring a nonnegative quantity rejects -2.

Create three fixtures: malformed XML, well-formed XML with a missing quantity, and a valid order. Explain which validation stage should reject each one.

Open the XML learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.