Web Technology IUnit 511 min read
XML: Structure, Syntax & Applications
Unit 5 of Web Technology I introduces Extensible Markup Language (XML), its syntax, document structure, validation, and real-world use cases like data exchange in e-commerce and banking systems. It covers XML declarations, elements, attributes, DTDs, and XSD schemas, along with practical examples like Daraz order data
1. Introduction to XML
XML (Extensible Markup Language) is a human- and machine-readable markup language designed to store and transport data. Unlike HTML (which defines how data is displayed), XML defines what the data is and its structure.
Key Features of XML
- Self-descriptive: Data is tagged with meaningful labels (e.g.,
<book>instead of<item>). - Platform-independent: Works across operating systems and programming languages.
- Extensible: Users can define their own tags (e.g.,
<order>,<product>).
XML vs. HTML
| Feature | XML | HTML |
|---|---|---|
| Purpose | Stores and transports data | Defines content presentation |
| Tags | User-defined (e.g., <book>) |
Predefined (e.g., <h1>, <p>) |
| Validation | Requires DTD/XSD | No validation needed |
| Example | <order id="101">...</order> |
<h1>Welcome</h1> |
2. XML Document Structure
An XML document follows a strict hierarchy with a root element and nested child elements.
Basic XML Syntax
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="101">
<title>XML Basics</title>
<author>John Doe</author>
<price>250</price>
</book>
<book id="102">
<title>Web Technologies</title>
<author>Jane Smith</author>
<price>300</price>
</book>
</library>
- XML Declaration:
<?xml version="1.0" encoding="UTF-8"?>(mandatory). - Root Element:
<library>(must enclose all other elements). - Child Elements:
<book>,<title>,<author>, etc. - Attributes:
id="101"(provides additional data about elements).
Rules for Valid XML
- XML is case-sensitive (
<Book>≠<book>). - All elements must have a closing tag (
<book></book>). - XML documents must have one root element.
- Attribute values must be quoted (
id="101"). - Comments are written as
<!-- This is a comment -->.
3. XML Elements and Attributes
Elements
- Containers for data (e.g.,
<book>,<title>). - Can be empty (e.g.,
<linebreak />) or self-closing (e.g.,<image src="book.jpg" />).
Attributes
- Provide additional information about elements.
- Example:
<book id="101" category="Programming"> <title>XML Basics</title> </book> - Best Practice: Use elements for complex data, attributes for simple metadata.
4. XML Namespaces
Namespaces prevent tag conflicts when mixing XML vocabularies (e.g., combining HTML and SVG).
Syntax
<root xmlns:ns1="http://example.com/ns1">
<ns1:element>Data</ns1:element>
</root>
- Example: In a Daraz order system, namespaces could separate product data (
<product xmlns:prod="...">) from shipping data (<shipping xmlns:ship="...">).
5. XML Validation
Validation ensures XML documents follow a defined structure using:
- Document Type Definition (DTD)
- XML Schema Definition (XSD)
DTD Example
<!DOCTYPE library [
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
#PCDATA: Parsed Character Data (text content).
XSD Example (Simplified)
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
- Advantages of XSD over DTD:
- Supports data types (
xs:decimal,xs:string). - More flexible (e.g.,
maxOccurs="unbounded").
- Supports data types (
6. XML Parsing
XML is parsed using DOM (Document Object Model) or SAX (Simple API for XML).
DOM Parsing (Tree Structure)
graph TD
A["Document"] --> B["library"]
B --> C["book 1"]
B --> D["book 2"]
C --> E["title"]
C --> F["author"]
C --> G["price"]- Pros: Random access to elements.
- Cons: Requires loading entire XML into memory.
SAX Parsing (Event-Driven)
- Processes XML line by line (memory-efficient).
- Used for large files (e.g., parsing NEPSE stock market data).
7. XML in Real-World Applications
In the Real World
Daraz (e-commerce)
- Idea: XML is used to exchange order data between Daraz’s backend and third-party logistics (3PL) systems.
- Example: An XML payload for an order might look like:
<order id="ORD-12345"> <customer>user123</customer> <items> <item> <product>Laptop</product> <quantity>1</quantity> </item> </items> <status>shipped</status> </order> - Why XML? Ensures structured data transfer between systems.
NEPSE (Stock Market)
- Idea: XML is used to publish stock market data in a standardized format.
- Example: A stock quote XML snippet:
<stock> <symbol>NEPSE</symbol> <price>1250.50</price> <volume>10000</volume> <timestamp>2024-05-20T10:00:00</timestamp> </stock> - Why XML? Allows apps (like Pathao’s investment tools) to parse and display data easily.
Khalti (Payment Gateway)
- Idea: XML is used to validate payment requests between merchants and Khalti’s servers.
- Example: A payment initiation XML:
<payment> <amount>500</amount> <currency>NPR</currency> <merchant_id>MERCH-123</merchant_id> <transaction_id>TXN-456</transaction_id> </payment> - Why XML? Ensures structured, tamper-proof data exchange.
8. Worked Example: Daraz Order Queue
Scenario: Daraz receives an XML order and processes it using XSD validation.
Step 1: XML Order Data
<order>
<order_id>ORD-789</order_id>
<customer>
<name>Ramesh</name>
<email>ramesh@example.com</email>
</customer>
<items>
<item>
<product_id>P100</product_id>
<quantity>2</quantity>
</item>
</items>
<total_amount>1500</total_amount>
</order>
Step 2: XSD Schema for Validation
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
<xs:complexType>
<xs:sequence>
<xs:element name="order_id" type="xs:string"/>
<xs:element name="customer">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="items">
<xs:complexType>
<xs:sequence>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="product_id" type="xs:string"/>
<xs:element name="quantity" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="total_amount" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Step 3: Validation Process
- Daraz’s backend parses the XML order.
- It checks against the XSD schema to ensure:
- All required fields (
order_id,customer,items) are present. quantityis an integer.total_amountis a decimal.
- All required fields (
- If valid, the order is queued for processing; if invalid, it’s rejected.
9. Advantages and Disadvantages of XML
| Advantages | Disadvantages |
|---|---|
| Human-readable and self-descriptive | Verbose (more code than JSON) |
| Platform-independent | Slower parsing than JSON |
| Supports complex data structures | Requires validation (DTD/XSD) |
| Used in enterprise systems (e.g., banks) | Not ideal for simple data (e.g., APIs) |
10. XML vs. JSON
| Feature | XML | JSON |
|---|---|---|
| Syntax | Tags (<tag>content</tag>) |
Key-value pairs ({"key": "value"}) |
| Readability | More verbose | Compact |
| Use Case | Enterprise data exchange | APIs, lightweight data |
| Example | <book><title>XML</title></book> |
{"book": {"title": "XML"}} |
Exam Tip
- Focus on:
- XML Declaration and root element rules.
- DTD vs. XSD (know when to use each).
- Parsing methods (DOM vs. SAX).
- Real-world applications (e.g., Daraz, NEPSE).
- Common Mistakes:
- Forgetting the XML declaration (
<?xml ...?>). - Mixing elements and attributes incorrectly.
- Not validating XML against a schema.
- Forgetting the XML declaration (
- Practical Question:
- "Write an XML document for a Pathao ride request with validation using XSD."
- "Explain how XML is used in Ncell’s SMS gateway for transaction data."
| Caption: A visual representation of XML’s hierarchical structure with root, parent, child, and sibling elements. |
| Caption: A snippet of an XSD schema validating a library XML document, showing data types and element constraints. |
| Caption: A flowchart of how Daraz uses XML to validate and process orders from merchants to logistics providers. |
| Caption: A real-world example of hardware (router) that might use XML for configuration data exchange in NTC’s network infrastructure. |
Based on the TU BIT syllabus for Web Technology I (BIT251), unit 5.
Discussion
Loading…