XML
Extensible Markup Language (XML) is a markup language that defines rules for encoding documents in a format that is both human-readable and machine-readable.
Overview
XML is a flexible markup language used to store and transport data. While less common in modern web development (JSON has largely replaced it for data exchange), XML is still used in configuration files, RSS feeds, SVG graphics, and various APIs. XML uses tags similar to HTML but allows you to define custom tag names.
Example
xml<!-- Basic XML structure --> <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="web"> <title>Learning JavaScript</title> <author>Jane Doe</author> <year>2024</year> <price>29.99</price> </book> <book category="programming"> <title>React Patterns</title> <author>John Smith</author> <year>2023</year> <price>34.99</price> </book> </bookstore> <!-- XML with attributes --> <person id="123" role="developer"> <name>Alice</name> <email>[email protected]</email> </person> <!-- SVG (XML-based graphics) --> <svg width="100" height="100"> <circle cx="50" cy="50" r="40" fill="blue" /> </svg> <!-- RSS Feed (XML-based) --> <rss version="2.0"> <channel> <title>My Blog</title> <link>https://myblog.com</link> <item> <title>First Post</title> <description>This is my first post</description> </item> </channel> </rss>
javascript// Parsing XML in JavaScript const xmlString = ` <users> <user id="1"> <name>Alice</name> </user> </users> `; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // Query XML const name = xmlDoc.querySelector('name').textContent; console.log(name); // 'Alice' // Create XML const doc = document.implementation.createDocument('', '', null); const root = doc.createElement('users'); const user = doc.createElement('user'); user.setAttribute('id', '1'); const name = doc.createElement('name'); name.textContent = 'Alice'; user.appendChild(name); root.appendChild(user); // Convert to string const serializer = new XMLSerializer(); const xmlString = serializer.serializeToString(root); // Fetch XML data fetch('/data.xml') .then(response => response.text()) .then(str => { const parser = new DOMParser(); const xml = parser.parseFromString(str, 'text/xml'); // Process XML });
Key Points
- Markup language for data storage and transport
- Self-descriptive with custom tags
- Strict syntax rules
- Less common than JSON for APIs
- Still used for SVG, RSS, configuration
Learn More
- XMLHttpRequest - AJAX requests
- JSON - Modern data format
- MDN: XML