Here’s the translation of the XML example from Go to Crystal, formatted in Markdown suitable for Hugo:
This Crystal code demonstrates XML parsing and generation using the XML module. Here’s a breakdown of the main components:
We define a Plant class that includes XML::Serializable for XML serialization and deserialization. We use annotations to control how the class is serialized to XML.
In the main function, we create Plant instances and demonstrate XML generation using to_xml.
We show how to parse XML back into Crystal objects using from_xml.
We create a Nesting class to demonstrate nested XML structures.
Finally, we generate nested XML using the Nesting class.
To run this program, save it as xml_example.cr and use the Crystal compiler:
This will output the generated XML structures and the parsed Plant object.
Crystal’s XML handling is similar to Go’s, but it uses annotations and modules instead of struct tags. The XML::Serializable module provides functionality similar to Go’s encoding/xml package.