Parsing XML Data

Extensible Markup Language (XML) is used to represent data in a structured way. It is a very common way to save data in text files. Indeed, Godot Engine uses XML files to store documentation data.

Extracting data from an XML file is done by Parsing the tree of elements which is like traversing over the file and filtering out the data that you want.

Godot provides the XMLParser class for this purpose.

Using the XMLParser class

This is quite low level and what it does is to read the data line by line and extract the properties of the data.

XML terminology usually refers to a tree of elements that have tags, but in Godot, they are a tree of nodes with names, just like in the scene tree.

XML Element in Godot:

<node_name attribute_name="attribute value">data</node_name>

To avoid getting errors, we should check the Node Type before extracting its data. Here is an example to extract the names of color constants for the Color.xml file:

func get_color_names():
	var color_names = []
	var parser = XMLParser.new()
	var error = parser.open("../Color.xml")
	if error != OK:
		print("Error opening XML file ", error)
		return
	
	while true:
		if parser.read() != OK:
			return color_names
		if parser.get_node_type() == parser.NODE_ELEMENT and parser.get_node_name() == "constant":
			var cname = parser.get_named_attribute_value_safe("name")
			color_names.append(cname)

In the example, it is a bit odd in a couple of ways:

We didn’t need to traverse the tree since our target nodes with a name of “constant” only appear in one group with a parent node called “constants”.

Using “name” for an attribute tag is not a good idea since that tag is ubiquitous in coding terminology for key reference names, what I tend to do is to use “title” instead.

Before writing parsing code, we should look at the data file to see how it is structured. Then we can decide if we need to drill down through the node tree to get to our target parent node or home in on the nodes containing the data directly.

We may skip inner nodes with the skip_section() method.

So that is a wrap for this tutorial about Parsing XML Data in Godot Engine.

More solutions