optional · CSS study notes
XML Documents & Web Services
Syllabus tag: Paper-II, Section-B, Topic IV.8 — XML Documents & Web Services
Definition
XML (eXtensible Markup Language) is a self-describing, hierarchical, vendor-independent markup format for representing and exchanging structured data — used heavily as the interchange format between heterogeneous database systems and across web services.
XML Structure
<?xml version="1.0"?>
<Student StudentID="101">
<Name>Ali Khan</Name>
<Department>Computer Science</Department>
</Student>
- Elements:
<Name>...</Name>— the basic building block, can nest - Attributes:
StudentID="101"— metadata on an element - Well-formed XML: obeys basic syntax rules (single root element, properly nested/closed tags, matching quotes) — required for ANY XML document
- Valid XML: well-formed AND conforms to a declared schema (DTD or XSD) — required only when a schema is specified
Schema Definition Languages
| Aspect | DTD (Document Type Definition) | XSD (XML Schema Definition) |
|---|---|---|
| Syntax | Own non-XML syntax | Written in XML itself |
| Data types | No real data typing (text only) | Rich data types (integer, date, string, custom types) |
| Namespaces | Not supported | Supported |
| Expressiveness | Limited structural constraints | Supports constraints like min/max occurrence, patterns |
Querying XML
- XPath: a path-expression language to navigate/select nodes within an XML document (e.g.,
/Student/Name) - XQuery: a full query language for XML (roughly XML's counterpart to SQL), built on XPath
XML & Databases
- XML provides a database-vendor-independent exchange format — two systems using completely different DBMS products can still exchange data reliably if both understand XML.
- Modern RDBMS (Oracle, SQL Server, PostgreSQL) offer native XML data types and functions to store and query XML fragments inside relational columns.
Web Services — SOAP vs REST
| Aspect | SOAP | REST |
|---|---|---|
| Style | Protocol (strict standard) | Architectural style (set of constraints) |
| Message format | XML only (SOAP envelope) | Any format — typically JSON, also XML |
| Transport | Can use HTTP, SMTP, etc. | Uses HTTP verbs directly (GET/POST/PUT/DELETE) |
| State | Can be stateful | Stateless by constraint |
| Overhead | Higher (verbose XML envelope, strict headers) | Lower, simpler |
| Contract | WSDL (Web Services Description Language) | No formal contract required (often OpenAPI/Swagger informally) |
- WSDL: an XML-based document describing a SOAP web service's operations, message formats, and endpoint — analogous to an API contract.
Java Web Services (the Java-specific stack)
Some CSS textbooks name this subtopic "Java Web Services" — the same SOAP/REST concepts above, expressed through Java's standard APIs.
- JAX-WS (Java API for XML Web Services): builds SOAP services; the service interface is annotated
@WebServiceand a WSDL is generated from it. - JAX-RS (Java API for RESTful Web Services): builds REST services using annotations such as
@Path,@GET,@POST,@Produces— reference implementation Jersey. - JAXB (Java Architecture for XML Binding): maps Java objects ↔ XML automatically (marshalling/unmarshalling), so an XML payload becomes a Java object without manual parsing.
- Typical database-backed flow: client request → JAX-RS/JAX-WS endpoint → business logic → JDBC / JPA to the RDBMS → result mapped back to XML/JSON → response.
- UDDI (Universal Description, Discovery and Integration): the (now largely obsolete) registry standard where SOAP services were published and discovered — worth one line if the question names it.
Why This Matters for Databases
- Web services (SOAP/REST) are the standard mechanism by which a database-backed application exposes its data to other systems over a network — XML/JSON is the payload format carried over that call.
MCQ Trap
- "Well-formed" ≠ "valid": every valid XML document must be well-formed, but a well-formed document need not be valid against any schema (it may have no schema at all).
- SOAP is a strict protocol with its own error-handling standard (SOAP Fault); REST simply reuses HTTP status codes — a frequent conceptual confusion point.
CSS Exam Angle
- This is the lowest past-paper frequency DB subtopic in the last decade of FPSC papers — but it is explicitly named in the syllabus, so expect it as a short note / MCQ rather than a full numerical, and prepare a tight definition + one comparison table (DTD vs XSD, or SOAP vs REST) as your go-to answer.
Likely Questions
- What is XML? Why is it used for data interchange between database systems?
- Differentiate a well-formed XML document from a valid one.
- Compare DTD and XSD as XML schema definition mechanisms.
- Compare SOAP and REST web services.
- What is WSDL, and what role does it play in a SOAP-based web service?
📘 Enrichment — Worked Examples
Example 1 — One XML Document, a DTD and an XSD for It
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE university SYSTEM "university.dtd">
<university>
<student regNo="S1">
<name>Ali</name>
<city>Lahore</city>
<cgpa>3.6</cgpa>
<course code="C1">DBMS</course>
<course code="C2">OS</course>
</student>
<student regNo="S2">
<name>Sara</name>
<city>Karachi</city>
<cgpa>3.9</cgpa>
<course code="C1">DBMS</course>
</student>
</university>
DTD (university.dtd):
<!ELEMENT university (student+)>
<!ELEMENT student (name, city, cgpa, course*)>
<!ATTLIST student regNo ID #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT cgpa (#PCDATA)>
<!ELEMENT course (#PCDATA)>
<!ATTLIST course code CDATA #REQUIRED>
- Occurrence symbols:
+one or more ·*zero or more ·?optional · none = exactly one. - Weakness visible here: the DTD cannot say that cgpa is a number between 0 and 4 — it is just text.
XSD fragment for the same student element — note the real data typing:
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="cgpa">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.0"/>
<xs:maxInclusive value="4.0"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="course" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="regNo" type="xs:ID" use="required"/>
</xs:complexType>
</xs:element>
Example 2 — XPath and XQuery with Results
| Expression | Result on the document above |
|---|---|
| /university/student/name | Ali, Sara |
| //student[city='Lahore']/name | Ali |
| //student[@regNo='S2']/cgpa | 3.9 |
| //course[@code='C1'] | DBMS, DBMS (one per student) |
count(//student[cgpa > 3.5]) | 2 |
/= child step from root,//= any descendant,@= attribute,[ ]= predicate/filter.
XQuery FLWOR (For–Let–Where–Order by–Return), the XML counterpart of SELECT–FROM–WHERE:
for $s in doc("university.xml")/university/student
where $s/cgpa > 3.5
order by $s/name
return <topper>{ $s/name/text() }</topper>
Result: <topper>Ali</topper><topper>Sara</topper>.
Example 3 — Publishing Relational Data as XML (SQL/XML)
SELECT XMLELEMENT(NAME "student",
XMLATTRIBUTES(s.RegNo AS "regNo"),
XMLELEMENT(NAME "name", s.Name),
XMLELEMENT(NAME "city", s.City))
FROM Student s;
- Direction 1: Publishing — relational rows → XML (as above).
- Direction 2: Shredding — XML document → relational rows (each repeating element becomes a row in a child table, e.g. course → Enrollment).
- Direction 3: Native storage — keep XML in an
XMLTYPE/xmlcolumn and query it with XPath.
XML vs JSON (modern follow-up)
| Aspect | XML | JSON |
|---|---|---|
| Syntax | Tags, attributes; verbose | Key–value pairs, arrays; compact |
| Schema | DTD / XSD (mature, strict) | JSON Schema (optional) |
| Query | XPath, XQuery, XSLT for transformation | JSONPath, native operators (PostgreSQL jsonb, MongoDB) |
| Typical use today | SOAP, office formats (.docx), banking/government messaging, configuration | REST APIs, NoSQL documents, web/mobile apps |
- The same student in JSON:
{"regNo":"S1","name":"Ali","city":"Lahore","cgpa":3.6,"courses":["DBMS","OS"]} - XML is still used heavily in financial messaging (ISO 20022), which interbank systems worldwide — including instant-payment systems — are adopting.
Example 4 — A REST Web Service over a Student Table
| HTTP request | Meaning | SQL executed by the service | Typical status |
|---|---|---|---|
| GET /students/S1 | Read one | SELECT … WHERE RegNo='S1' | 200 OK / 404 Not Found |
| GET /students?city=Lahore | Search | SELECT … WHERE City='Lahore' | 200 OK |
| POST /students | Create | INSERT INTO Student … | 201 Created |
| PUT /students/S1 | Replace/update | UPDATE Student … WHERE RegNo='S1' | 200 OK |
| DELETE /students/S1 | Delete | DELETE FROM Student WHERE RegNo='S1' | 204 No Content |
- A SOAP version would instead expose operations such as
getStudent(regNo)described in a WSDL, with every request wrapped in an XML envelope (Envelope → Header → Body → Fault).
Web Service Architecture (SOA triangle)
flowchart LR
P["Service Provider"] -- "1. publish (WSDL)" --> R["Service Registry (UDDI)"]
C["Service Consumer"] -- "2. find" --> R
C -- "3. bind & invoke (SOAP/HTTP)" --> P
P --> DB[("Database")]
✍️ Model Answers — Likely Questions
Q1. What is XML and why is it used for data interchange between databases?
Definition: a W3C-standard, text-based, self-describing markup language for structured and semi-structured data, with user-defined tags.
Why for interchange: (1) platform- and vendor-neutral plain text; (2) self-describing — tags carry meaning; (3) hierarchical, so it represents nested records naturally; (4) validated against DTD/XSD so receivers can trust structure; (5) mature tooling (parsers, XPath, XSLT) and native support in Oracle/SQL Server/PostgreSQL.
Example: an Oracle-based university system exports results as XML that an HEC system on SQL Server imports after XSD validation.
Limitation: verbose → JSON preferred for lightweight web APIs.
Q2. Differentiate a well-formed XML document from a valid one.
- Well-formed: obeys XML syntax — exactly one root element, every tag closed, properly nested, case-sensitive matching tags, quoted attribute values, no duplicate attributes.
- Valid: well-formed and conforms to its DTD/XSD (right elements, order, occurrence, types).
- Relationship: valid ⊂ well-formed. Example: omitting
<cgpa>in a student keeps the document well-formed but makes it invalid against the DTD above; leaving<name>unclosed makes it not even well-formed.
Q3. Compare DTD and XSD.
Use the comparison table in the notes, then show the same student element in both (Example 1): the DTD treats cgpa as text; the XSD restricts it to a decimal between 0.0 and 4.0 and supports namespaces and min/max occurrence. Conclude that XSD is the modern choice; DTD survives for simple and legacy documents.
Q4. Compare SOAP and REST web services.
Use the SOAP vs REST table, then add: REST maps naturally to database CRUD (Example 4 table); SOAP brings built-in standards (WS-Security, WS-ReliableMessaging, WS-AtomicTransaction) valued in banking/enterprise integration. Conclude: REST dominates public and mobile APIs; SOAP persists where formal contracts and enterprise security standards matter.
Q5. What is WSDL and its role in a SOAP web service?
WSDL is an XML document acting as the service's contract: types (XSD data types), messages, portType/interface (operations such as getStudent), binding (SOAP over HTTP) and service/port (endpoint URL). Clients use it to auto-generate stubs, so a Java client can call a .NET service without knowing its implementation. It is published in a registry (UDDI) in the classic SOA triangle — draw the diagram above.
⚡ 60-Second Revision
- Valid ⇒ well-formed, not vice-versa.
- DTD: non-XML syntax, no types, no namespaces. XSD: XML syntax, rich types, namespaces.
- XPath navigates (/, //, @, predicates); XQuery = FLWOR.
- SOAP = protocol, XML envelope, WSDL, WS-* security. REST = style, HTTP verbs, stateless, usually JSON.
- SOA triangle: provider publishes → registry → consumer finds → binds.