Xml in GDScript

extends Node

# Plant will be mapped to XML. We use a Dictionary to represent
# the structure, as GDScript doesn't have built-in XML support.
class Plant:
    var id: int
    var name: String
    var origin: Array

    func _init(id: int, name: String, origin: Array = []):
        self.id = id
        self.name = name
        self.origin = origin

    func to_string() -> String:
        return "Plant id=%d, name=%s, origin=%s" % [id, name, origin]

func _ready():
    var coffee = Plant.new(27, "Coffee", ["Ethiopia", "Brazil"])

    # Emit XML representing our plant
    var xml = to_xml(coffee)
    print(xml)

    # To add a generic XML header to the output, prepend it explicitly
    print('<?xml version="1.0" encoding="UTF-8"?>\n' + xml)

    # Parse XML string into a Plant object
    var parsed_plant = parse_xml(xml)
    print(parsed_plant.to_string())

    var tomato = Plant.new(81, "Tomato", ["Mexico", "California"])

    # Create a nested structure
    var nesting = {
        "nesting": {
            "parent": {
                "child": {
                    "plant": [coffee, tomato]
                }
            }
        }
    }

    var nested_xml = to_xml(nesting)
    print(nested_xml)

func to_xml(data) -> String:
    # This is a simple XML conversion function. For more complex scenarios,
    # you might want to use a dedicated XML library.
    if data is Plant:
        var xml = ' <plant id="%d">\n' % data.id
        xml += '   <name>%s</name>\n' % data.name
        for origin in data.origin:
            xml += '   <origin>%s</origin>\n' % origin
        xml += ' </plant>'
        return xml
    elif data is Dictionary:
        var xml = ""
        for key in data:
            xml += " <%s>\n" % key
            if data[key] is Array:
                for item in data[key]:
                    xml += to_xml(item) + "\n"
            else:
                xml += to_xml(data[key])
            xml += " </%s>\n" % key
        return xml
    else:
        return str(data)

func parse_xml(xml: String) -> Plant:
    # This is a very basic XML parsing function.
    # For real-world use, consider using a proper XML parsing library.
    var id_regex = RegEx.new()
    id_regex.compile('id="(\\d+)"')
    var name_regex = RegEx.new()
    name_regex.compile('<name>(.*?)</name>')
    var origin_regex = RegEx.new()
    origin_regex.compile('<origin>(.*?)</origin>')

    var id = int(id_regex.search(xml).get_string(1))
    var name = name_regex.search(xml).get_string(1)
    var origins = []
    for origin_match in origin_regex.search_all(xml):
        origins.append(origin_match.get_string(1))

    return Plant.new(id, name, origins)

This GDScript code demonstrates XML-like functionality using dictionaries and strings, as GDScript doesn’t have built-in XML support. Here’s what the code does:

  1. We define a Plant class to represent our data structure.

  2. In the _ready function (equivalent to main in Go), we create instances of Plant and demonstrate XML conversion.

  3. The to_xml function converts our data structures to XML-like strings.

  4. The parse_xml function demonstrates basic XML parsing using regular expressions.

  5. We also show how to create nested structures using dictionaries and convert them to XML-like format.

To run this script, you would need to attach it to a Node in a Godot scene. The output would be similar to the Go example, showing the XML representation of the plants and the nested structure.

Note that this is a simplified representation of XML handling. For more complex XML operations in GDScript, you might want to use a dedicated XML parsing library or implement more robust XML handling functions.