Need some help understanding how to utilize core:encoding/xml

Here is a snippet parsing an XML document, checking that the root node is a “map” and then looping through its children:

doc, err := xml.parse(data, xml.Options{
	flags={.Ignore_Unsupported},
	expected_doctype="",
})

if err != nil {
	panic("Failed to parse XML")
}

root := &doc.elements[0]
// Check that root element is a "map" element
assert(root.ident == "map")

// Loop through children
for child_value in root.value {
	switch child in child_value {
	case string:
		// Not expecting text inside root noed
		panic(fmt.tprintf("Unexpected string: \"%s\"", child))
	case xml.Element_ID:
		child_node := &doc.elements[child]
		if child_node.ident == "tileset" {
			// TODO: handle "tileset" node
		} else if child_node.ident == "layer" {
			// TODO: handle "layer" node
		} else {
			// Something we don't care about
			fmt.printfln("Skipping top level node: %s", child_node.ident)
		}
	}
}

You can search through attributes of a node like this:

get_attrib :: proc(element: ^xml.Element, key: string) -> (string, bool) {
	for attrib in element.attribs {
		if attrib.key == key {
			return attrib.val, true
		}
	}

	return "", false
}

Hope that gets you started.

2 Likes