What is XML?

XML (eXtensible Markup Language) is a flexible, structured format used for storing and exchanging data. It is human-readable and machine-friendly, making it widely used in web services, configuration files, and data transport.

1. Why Use XML?

2. XML Syntax

XML uses tags similar to HTML but follows stricter rules:

Example XML Data

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>John Doe</name>
    <age>30</age>
    <email>johndoe@example.com</email>
    <address>
        <street>123 Main St</street>
        <city>New York</city>
        <zip>10001</zip>
    </address>
</person>

3. XML Elements and Attributes

Elements

<name>John Doe</name>

Attributes

<person id="12345">
    <name>John Doe</name>
</person>

4. XML vs. JSON

Feature XML JSON
Readability Verbose, but structured More concise
Data Storage Hierarchical with tags Key-value pairs
Use Case Config files, SOAP APIs REST APIs, lightweight data exchange

5. Parsing XML

In JavaScript

let parser = new DOMParser();
let xmlString = `<person><name>John Doe</name></person>`;
let xmlDoc = parser.parseFromString(xmlString, "text/xml");
console.log(xmlDoc.getElementsByTagName("name")[0].textContent); // Output: John Doe

In Python

import xml.etree.ElementTree as ET

xml_data = "<person><name>John Doe</name></person>"
root = ET.fromstring(xml_data)
print(root.find("name").text)  # Output: John Doe

6. XML in Web Services

SOAP (Simple Object Access Protocol)

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <GetWeather>
            <City>New York</City>
        </GetWeather>
    </soap:Body>
</soap:Envelope>

RSS Feeds

<rss version="2.0">
    <channel>
        <title>News Updates</title>
        <item>
            <title>Breaking News</title>
            <description>Something big happened!</description>
        </item>
    </channel>
</rss>

7. Validating XML

XML can be validated using:

Conclusion

XML is a versatile, structured format that is widely used for data storage, APIs, and configuration. Although JSON has become more popular for web APIs, XML is still valuable in enterprise systems and structured document storage.