Here’s the translation of the XML example from Go to Java, formatted in Markdown suitable for Hugo:
Our program demonstrates working with XML in Java. We’ll use the JAXB (Java Architecture for XML Binding) API, which is part of the Java SE platform.
First, let’s define our Plant class:
In this class, we use JAXB annotations to specify how the object should be mapped to XML. The @XmlRootElement annotation specifies the name of the root XML element, and @XmlAttribute and @XmlElement annotations mark fields as XML attributes or elements respectively.
Now, let’s create our main class to demonstrate XML marshalling and unmarshalling:
This program demonstrates XML marshalling (converting objects to XML) and unmarshalling (parsing XML back into objects). We also show how to create nested XML structures.
To run this program, you’ll need to compile and execute it:
The output will show the XML representations of our Plant and Nesting objects, demonstrating both simple and nested XML structures.
Note that JAXB is included in Java SE 8 and earlier versions. For Java SE 9 and later, you might need to add JAXB as a dependency to your project.
This example showcases basic XML handling in Java, including object-to-XML mapping, formatting output, and parsing XML back into objects.