XML, or Extensible Markup Language, is a markup language used to store and transport data. It's similar to HTML, but unlike HTML, XML doesn't have predefined tags. Instead, it allows you to create your own, making it highly flexible and platform-independent.
An XML document consists of elements, which can contain other elements, text, and attributes.
Example:
<contact>
<name>John Doe</name>
<email>john.doe@example.com</email>
<phone>123-456-7890</phone>
</contact>In this example, contact, name, email, and phone are elements. name, email, and phone have text inside them. The name element has an attribute xmlns which is used to specify the XML namespace.
An XML document starts with a declaration that defines the version of XML and the XML encoding.
Example:
<?xml version="1.0" encoding="UTF-8"?>Let's create a simple XML file for a contact list.
First, let's define the structure of our XML document.
<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<!-- Contacts will be added here -->
</contactList>Now, let's add some contacts to our contact list.
<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<contact>
<name>John Doe</name>
<email>john.doe@example.com</email>
<phone>123-456-7890</phone>
</contact>
<contact>
<name>Jane Smith</name>
<email>jane.smith@example.com</email>
<phone>987-654-3210</phone>
</contact>
</contactList>To work with XML in Python, we can use the xml.etree.ElementTree module. Here's how you can parse our contact list XML.
import xml.etree.ElementTree as ET
# Parse the XML
tree = ET.parse('contact_list.xml')
# Get the root element (contactList)
root = tree.getroot()
# Iterate through contacts
for contact in root.findall('contact'):
name = contact.find('name').text
email = contact.find('email').text
phone = contact.find('phone').text
print(f"Name: {name}, Email: {email}, Phone: {phone}")Question: Which tag is used to define the structure of an XML document?
A: document
B: xml
C: root
Correct: B
Explanation: The xml tag is used to define the structure of an XML document. The xml tag should contain an XML declaration and the root element of the document.
Keep learning, coding, and crafting with CodeYourCraft! 🚀