#dataSource #U3-AOS1 #U3-AOS1-KK6
[[Outcome 1 - Programming#6. characteristics of data sources (plain text (TXT), delimited (CSV) and XML files), including | U3 - AOS1 - KK6]]
# XML Structure
XML (Extensible Markup Language) is a markup language designed to store and transport data in a structured and human-readable format. The XML structure consists of the following components:
1. **Elements**: Elements are the building blocks of XML and are defined by a start tag, an end tag, and the content in between. Elements can contain other elements, creating a hierarchical structure known as the "element tree."
2. **Attributes**: Attributes provide additional information about an element and are defined within the start tag of an element. They consist of a name-value pair, with the name being unique within the element.
3. **Text content:** Text content is the actual data or information stored within an element.
Declaration: XML documents usually start with an XML declaration, which defines the XML version and encoding used in the document.
# Python XML Manipulation Tutorial
This guide covers how to parse, navigate, modify, and save XML files using Python's built-in `xml.etree.ElementTree` library.
## 1. The XML Structure (`xml_file.xml`)
We start with a sample XML file containing student data.
```XML
<?xml version="1.0" encoding="UTF-8"?>
<data date="2025-10-10">
<student>
<name>Bob</name>
<class>Coding</class>
<attendance>90%</attendance>
</student>
<student>
<name>Alice</name>
<class>Coding</class>
<attendance>80%</attendance>
</student>
</data>
```
**Tree Representation:**
Plaintext
```
data (date="2025-10-10") <- root
├── student (root[0])
│ ├── name: Bob (root[0][0])
│ ├── class: Coding (root[0][1])
│ └── attendance: 90% (root[0][2])
└── student (root[1])
├── name: Alice (root[1][0])
├── class: Coding (root[1][1])
└── attendance: 80% (root[1][2])
```
---
## 2. Loading an XML
To begin, import the library and parse the existing file to get the root element.
```python
import xml.etree.ElementTree as ET
# Parse the existing xml file
tree = ET.parse('xml_file.xml')
root = tree.getroot()
```
---
## 3. Accessing the Root Element
You can access the tag name and check the number of direct children the root has.
```python
# Accessing the root
print(root.tag)
print(len(root))
```
**Output:**
Plaintext
```
data
2
```
---
## 4. Accessing the Root Child
You can access specific children using index notation. Here we access the first student (index 0).
```python
# Access root child
print(root[0].tag)
print(len(root[0]))
```
**Output:**
Plaintext
```
student
3
```
---
## 5. Loop Over Root Children
You can iterate through children of the root (the `student` elements) and access their sub-elements (like `name` at index 0).
```python
# Loop over root children
for child in root:
print(child[0].tag)
print(child[0].text)
```
**Output:**
Plaintext
```
name
Bob
name
Alice
```
---
## 6. Accessing the Root Grandchild
You can chain indices to access "grandchildren" elements (nested tags) deeply.
```python
# Root grandchildren
# Bob's Name (Student 0, child 0)
print(root[0][0].tag)
print(root[0][0].text)
# Bob's Class (Student 0, child 1)
print(root[0][1].tag)
print(root[0][1].text)
# Alice's Attendance (Student 1, child 2)
print(root[1][2].tag)
print(root[1][2].text)
```
**Output:**
Plaintext
```
name
Bob
class
Coding
attendance
80%
```
---
## 7. Create a New Element
You can create new elements programmatically and append them to the tree.
```python
# Create a new element (child)
new_child = ET.Element('newChildTag')
# Optionally add text or more sub-elements
new_child.text = 'Some text in this new element'
# Append the new child to the root
root.append(new_child)
# Optionally, you could also append to a specific child of root, for example:
# root[0].append(new_child)
# Write the modified xml back to a file
tree.write('updated_xml_file.xml')
```
---
## 8. Access an Element's Attribute
Attributes (like `date="2025-10-10"` in the root) are stored as a dictionary.
```python
print(root.attrib)
```
**Output:**
Plaintext
```
{'date': '2025-10-10'}
```
---
## 9. Find Elements with a Specific Tag
Use `.iter()` to find all elements with a specific tag name, regardless of their depth in the tree.
```python
# .iter('name') will yield every 'name' element within the tree
for name_elem in root.iter('name'):
print(name_elem.text)
```
**Output:**
Plaintext
```
Bob
Alice
```