Web TechnologyUnit 313 min read
XML, XSL, XSLT: Schemas, Paths, and Transformations
Unit 3 of Web Technology covers XML’s syntax and validation (DTD vs. XSD), XPath for data navigation, and XSL/XSLT for transforming XML into HTML or other formats. Learn how to structure data hierarchically, validate it rigorously, and style it dynamically—with real-world examples from eSewa’s transaction logs and Dara
TAKEAWAYS
- XML is a human- and machine-readable markup language for structured data, with strict rules for well-formedness (e.g., proper nesting, closing tags).
- DTD (Document Type Definition) and XSD (XML Schema Definition) validate XML structure, but XSD is more powerful (data types, namespaces, complex patterns).
- XPath lets you navigate XML like a file system (e.g.,
/student/address[1]/cityselects the first student’s city). - XSL/XSLT transforms XML into HTML, text, or other XML formats using templates and conditional logic (e.g., filtering Daraz products with
quantity < 10). - Real-world uses: eSewa’s transaction logs (XML for payments), Khalti’s merchant data (XSD validation), NTC’s service requests (XSLT to generate PDF reports).
- Exam focus: Write XML/DTD/XSD/XSLT snippets, compare validation methods, and explain XPath/XSLT syntax.
1. XML Fundamentals: Syntax and Well-Formedness
XML (eXtensible Markup Language) is a text-based format for storing and transporting structured data. Unlike HTML (which defines how to display content), XML defines what the data means.
Rules for Well-Formed XML
A valid XML document must follow these 10 golden rules (memorize these for exams!):
- Single root element: Every XML has exactly one root (e.g.,
<students>). - Proper nesting: Tags must open and close in the correct order (no overlapping).
- Closing tags: Every opening tag (
<tag>) must have a closing tag (</tag>), except empty elements (<tag/>). - Case sensitivity:
<Name>≠<name>. - Attribute values in quotes: Always use
" "or' '(e.g.,<student id="101">). - No unescaped characters: Use
<,>,&for<,>,&. - Comments: Wrap comments in
<!-- -->(e.g.,<!-- Student data -->). - No mixed content: Avoid
<p>Text <b>bold</b> more text</p>(use nested tags instead). - Encoding declaration: Start with
<?xml version="1.0" encoding="UTF-8"?>. - Whitespace handling: XML parsers ignore extra spaces/tabs (but preserve them if needed).
Example: Well-Formed XML for a Student
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="101">
<name>
<first_name>Ramesh</first_name>
<middle_name>K</middle_name>
<last_name>Adhikari</last_name>
</name>
<address city="KTM">Thapathali</address>
<rollno>2078123</rollno>
</student>
</students>
Common Mistakes (Avoid in Exams!)
- ❌ Missing closing tag:
<student><name>Ramesh</student>(invalid). - ❌ Unescaped
<:<price>100<</price>→ Use<instead. - ❌ Multiple roots:
<student>...</student><student>...</student>(invalid).
2. XML Validation: DTD vs. XSD
XML alone doesn’t enforce structure—you need validation schemas (DTD or XSD) to define rules.
A. DTD (Document Type Definition)
- Older, simpler method for validating XML.
- Defined inside the XML file (or in an external
.dtdfile). - Limitations:
- No data types (e.g., can’t enforce
rollnomust be numeric). - No namespaces support.
- Limited to basic structure rules.
- No data types (e.g., can’t enforce
B. XSD (XML Schema Definition)
- Modern, powerful alternative to DTD.
- Defined in a separate
.xsdfile (or inline). - Supports:
- Data types (
xs:int,xs:string,xs:date). - Complex patterns (e.g.,
minLength="8"for usernames). - Namespaces and inheritance.
- Data types (
Comparison Table
| Feature | DTD | XSD |
|---|---|---|
| Data Types | ❌ No | ✅ Yes (xs:int, xs:string) |
| Namespaces | ❌ No | ✅ Yes |
| Complex Patterns | ❌ Limited | ✅ Yes (e.g., regex) |
| File Format | Internal/External .dtd |
External .xsd |
| Example Use | Simple logs (e.g., server logs) | Financial data (e.g., NEPSE trades) |
REAL WORLD
- eSewa’s transaction logs use XML + XSD to validate payment details (e.g.,
amountmust be numeric,transaction_idmust be 12 digits). - Khalti’s merchant data uses XSD to enforce rules like
merchant_idformat (KLT-[A-Z]{3}-\d{6}). - NTC’s service request system uses DTD for simple forms (e.g.,
request_typecan only be "electricity" or "water").
Worked Example: XSD for Student Data
Given XML:
<student>
<name>
<first_name>Sita</first_name>
<last_name>Bhandari</last_name>
</name>
<address city="LPT">Bhaktapur</address>
<rollno>2078456</rollno>
</student>
XSD Schema:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="nameType"/>
<xs:element name="address" type="addressType"/>
<xs:element name="rollno" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="nameType">
<xs:sequence>
<xs:element name="first_name" type="xs:string"/>
<xs:element name="last_name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="addressType">
<xs:attribute name="city" type="xs:string" use="required"/>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="municipality" type="xs:string" default="Kathmandu"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>
Key Rules Enforced:
rollnomust be an integer.addressmust have acityattribute.namemust have bothfirst_nameandlast_name.
3. XPath: Navigating XML Like a File System
XPath (XML Path Language) lets you query XML data using path expressions, similar to navigating folders in Windows.
XPath Syntax Cheat Sheet
| Expression | Meaning | Example |
|---|---|---|
/ |
Root element | /students |
// |
Anywhere in the document | //student |
@ |
Attribute | @city |
[] |
Predicate (filter) | //student[@rollno="101"] |
/ + / |
Child element | /students/student |
[position()] |
Nth node | //student[1] (first student) |
text() |
Text content | //name/text() |
Worked Example: XPath Queries
Given XML:
<students>
<student id="101">
<name><first_name>Ramesh</first_name></name>
<address city="KTM">Thapathali</address>
</student>
<student id="102">
<name><first_name>Sita</first_name></name>
<address city="PKR">Lalitpur</address>
</student>
</students>
| XPath Expression | Result |
|---|---|
/students/student |
Both student nodes |
//student[@id="102"] |
Only Sita’s student node |
//address[@city="KTM"] |
Thapathali address node |
//name/first_name |
"Ramesh", "Sita" |
//student[1]/name |
Ramesh’s name node |
REAL WORLD
- Daraz’s product catalog uses XPath to filter items (e.g.,
//product[@category="electronics" and @price < 5000]). - NEPSE’s stock data uses XPath to extract closing prices:
//stock[@symbol="NEPSE"]/close.
4. XSL/XSLT: Transforming XML to HTML or Other Formats
XSL (eXtensible Stylesheet Language) has two parts:
- XSL-FO: For formatting (e.g., PDFs).
- XSLT: For transforming XML into HTML, text, or other XML.
Key Components of XSLT
<xsl:template>: Defines how to process elements.<xsl:value-of>: Extracts text content.<xsl:for-each>: Loops through nodes.<xsl:if>: Conditional logic.<xsl:apply-templates>: Recursively processes child nodes.
Worked Example: XSLT to Filter Daraz Products
Given XML (Daraz products):
<products>
<product>
<name>Laptop</name>
<category>Electronics</category>
<price>50000</price>
<quantity>5</quantity>
</product>
<product>
<name>Phone</name>
<category>Electronics</category>
<price>20000</price>
<quantity>15</quantity>
</product>
</products>
XSLT to Filter quantity < 10:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Products with Quantity < 10</h2>
<table border="1">
<tr><th>Name</th><th>Price</th><th>Quantity</th></tr>
<xsl:for-each select="products/product[quantity < 10]">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="price"/></td>
<td><xsl:value-of select="quantity"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output HTML:
<table border="1">
<tr><th>Name</th><th>Price</th><th>Quantity</th></tr>
<tr>
<td>Laptop</td>
<td>50000</td>
<td>5</td>
</tr>
</table>
REAL WORLD
- NTC’s service request system uses XSLT to convert XML request logs into PDF reports for engineers.
- Pathao’s driver app uses XSLT to transform XML trip data into JSON for the mobile frontend.
flowchart LR
A["XML Data"] --> B["XSLT Processor"]
B --> C["HTML Output"]
B --> D["PDF Output"]
B --> E["Other XML"]
C --> F["Browser Display"]
D --> G["Printed Report"]5. XSL vs. CSS: Key Differences
| Feature | XSL | CSS |
|---|---|---|
| Purpose | Transforms XML to other formats | Styles HTML/XML for display |
| Language | XML-based (XSLT) | CSS syntax |
| Use Case | Convert XML to HTML/PDF | Change fonts, colors, layout |
| Example | xsl:value-of |
color: red; |
REAL WORLD
- CSS styles a webpage’s appearance (e.g., Daraz’s product page colors).
- XSLT converts backend XML data (e.g., Daraz’s inventory XML) into HTML for the frontend.
6. Common Exam Questions and How to Answer
Q1: Compare XML Schema (XSD) with DTD.
Answer Structure:
- Definition: Briefly define both.
- Comparison Table: Use the table above (data types, namespaces, etc.).
- Example: Show a snippet of each validating the same XML.
Q2: Write XSD for a Student with name, address, and rollno.
Steps:
- Define the root element (
<xs:element name="student">). - Use
<xs:complexType>for nested elements (name,address). - Enforce data types (
xs:integerforrollno). - Add attributes if needed (e.g.,
cityinaddress).
Q3: Write XSLT to Filter Products with quantity < 10.
Steps:
- Start with
xsl:stylesheetdeclaration. - Use
xsl:template match="/". - Loop with
xsl:for-each select="products/product[quantity < 10]". - Extract values with
xsl:value-of.
Q4: Explain XPath with Examples.
Answer:
- Define XPath as a "path language for XML."
- Give 3-4 examples (e.g.,
/students/student,//address[@city="KTM"]). - Relate to real-world use (e.g., Daraz filtering).
classDiagram
class XSLTProcessor {
+applyStylesheet(xml: XML, xslt: XSLT) Output
}
class XML {
<<interface>>
+getRoot() Node
}
class XSLT {
<<interface>>
+getTemplate(element: String) Template
}
class Output {
<<interface>>
+toHTML() String
+toPDF() Byte[]
}
XSLTProcessor --> XML
XSLTProcessor --> XSLT
XSLTProcessor --> OutputExam Tip
For XML/XSD/DTD questions:
- Always start with
<?xml version="1.0"?>. - Use proper indentation (examiners love this!).
- Validate your XML against the schema you write.
- Always start with
For XPath/XSLT:
- Practice on sample XML (like the student/product examples above).
- Memorize common predicates (
[position()=1],[@attr="value"]).
Comparisons (XSD vs. DTD, XSL vs. CSS):
- Use tables to score easy marks.
- Highlight one key advantage of the modern method (e.g., XSD’s data types).
Real-world tie-ins:
- Mention eSewa/Khalti for XSD validation.
- Mention Daraz/NTC for XPath/XSLT filtering.
sequenceDiagram
participant User
participant XMLDocument
participant SchemaValidator
participant DTDorXSD
User->>XMLDocument: Provides XML
XMLDocument->>SchemaValidator: Validate()
SchemaValidator->>DTDorXSD: Check rules
alt Valid
DTDorXSD-->>SchemaValidator: ✅ Pass
else Invalid
DTDorXSD-->>SchemaValidator: ❌ Fail
end
SchemaValidator-->>User: ResultBased on the TU BCA syllabus for Web Technology (CACS205), unit 3.
Discussion
Loading…