XML
XML (Extensible Markup Language) stores data as a tree of named elements with optional attributes. It is older and wordier than JSON, but it is everywhere in data work: office documents (.docx, .xlsx are zipped XML), RSS feeds, government and banking data exchange, medical records, maps (OpenStreetMap, GPX tracks), and several classic ML annotation formats, most famously Pascal VOC for object detection. The XML course teaches the syntax and the DOM; here we read XML into tables for ML.
An annotation file in Pascal VOC style
<annotation>
<filename>street_001.jpg</filename>
<size><width>640</width><height>480</height><depth>3</depth></size>
<object>
<name>person</name><difficult>0</difficult>
<bndbox><xmin>100</xmin><ymin>120</ymin><xmax>160</xmax><ymax>300</ymax></bndbox>
</object>
<object>
<name>bicycle</name><difficult>1</difficult>
<bndbox><xmin>90</xmin><ymin>220</ymin><xmax>230</xmax><ymax>310</ymax></bndbox>
</object>
</annotation>Compare it with the COCO JSON of the annotation lesson: the same two boxes, but VOC stores corner coordinates (xmin, ymin, xmax, ymax) while COCO stores x, y, width, height. Mixing up the two conventions is one of the most common bugs in object-detection data.
Parsing with ElementTree
Python's standard library parses XML with xml.etree.ElementTree. find gets the first matching child, findall all of them, .text the content and .get an attribute:
import xml.etree.ElementTree as ET
import pandas as pd
xml = """<annotation>
<filename>street_001.jpg</filename>
<size><width>640</width><height>480</height><depth>3</depth></size>
<object>
<name>person</name><difficult>0</difficult>
<bndbox><xmin>100</xmin><ymin>120</ymin><xmax>160</xmax><ymax>300</ymax></bndbox>
</object>
<object>
<name>bicycle</name><difficult>1</difficult>
<bndbox><xmin>90</xmin><ymin>220</ymin><xmax>230</xmax><ymax>310</ymax></bndbox>
</object>
</annotation>"""
root = ET.fromstring(xml)
fname = root.findtext("filename")
rows = []
for obj in root.findall("object"):
box = obj.find("bndbox")
xmin, ymin, xmax, ymax = (int(box.findtext(k)) for k in ["xmin", "ymin", "xmax", "ymax"])
rows.append({
"file": fname,
"class": obj.findtext("name"),
"difficult": obj.findtext("difficult") == "1",
"coco_bbox": [xmin, ymin, xmax - xmin, ymax - ymin],
})
print(pd.DataFrame(rows)) file class difficult coco_bbox
0 street_001.jpg person False [100, 120, 60, 180]
1 street_001.jpg bicycle True [90, 220, 140, 90]
Every value comes out of XML as text; the code converts numbers and flags itself. The last column converts the corners to the COCO convention (width = xmax - xmin, height = ymax - ymin), and the result matches the COCO boxes 10 and 11 from the annotation lesson.
Attributes and pandas.read_xml
Flat, record-like XML (one element per row) can go straight into pandas. This example has values in both attributes and child elements:
import io
import pandas as pd
xml = """<stations>
<station id="S1" city="Hanoi"><temp unit="C">31.5</temp><humidity>78</humidity></station>
<station id="S2" city="Hue"><temp unit="C">29.0</temp><humidity>81</humidity></station>
<station id="S3" city="Sapa"><temp unit="F">60.8</temp><humidity>90</humidity></station>
</stations>"""
df = pd.read_xml(io.StringIO(xml), parser="etree")
print(df)
print()
temps = pd.read_xml(io.StringIO(xml), xpath=".//temp", parser="etree")
print(temps) id city temp humidity
0 S1 Hanoi 31.5 78
1 S2 Hue 29.0 81
2 S3 Sapa 60.8 90
unit temp
0 C 31.5
1 C 29.0
2 F 60.8
The first read turns each <station> into a row with its attributes and child texts, but it loses the unit attribute of <temp>, which sits one level deeper. Reading .//temp separately shows it: station S3 reports Fahrenheit. 60.8 °F is 16 °C, plausible for the mountain town of Sapa; treated as Celsius it would look like a heat record. XML keeps such details in attributes, and a careless flattening throws them away.
Safety
XML parsers can be attacked with crafted files: entity expansion ("billion laughs") makes a tiny file expand to gigabytes, and external entities can make the parser read local files. When you parse XML from untrusted sources (uploads, scraped pages), use the defusedxml package, which blocks these features, or a parser configured to disable them.
Pitfalls
- Everything is text. Convert numbers, booleans and dates explicitly.
- Attributes vs elements. Data can live in either; check both before flattening.
- Namespaces. Real files often declare
xmlns="…", and thenfind("name")finds nothing; you need{namespace}nameor a namespace map. - Coordinate conventions. VOC corners vs COCO width/height, 0-based vs 1-based pixels.
Practice
- Convert the COCO box
[600, 200, 80, 150]to VOC corners.
Answer
xmin = 600, ymin = 200, xmax = 600 + 80 = 680, ymax = 200 + 150 = 350. With an image width of 640, xmax lies outside the image, the same error found in the annotation lesson.
- Why did
read_xmlon<station>elements not produce aunitcolumn?
Answer
read_xml turns the attributes and the direct child texts of each selected element into columns. unit is an attribute of the child <temp>, one level deeper, so it is not collected.
Test yourself
A Pascal VOC box is xmin=50, ymin=40, xmax=150, ymax=100. What is it in COCO [x, y, width, height] form?
- [50, 40, 150, 100]
- [50, 40, 100, 60]
- [100, 70, 100, 60]
- [40, 50, 60, 100]
What type does findtext return for <xmax>160</xmax>?
- int
- float
- str
- bytes
Why should untrusted XML be parsed with defusedxml or a hardened parser?
- It is faster
- Crafted entities can blow up memory or read local files
- It converts types automatically
- ElementTree cannot read attributes