Our example demonstrates XML processing in Java using the JAXB (Java Architecture for XML Binding) API. This API provides a convenient way to marshal Java objects into XML and unmarshal XML back into Java objects.
First, let’s define our Plant class:
In this class, we use JAXB annotations to specify how the object should be represented in XML. The @XmlRootElement annotation defines the name of the root XML element, while @XmlAttribute and @XmlElement annotations specify which fields should be attributes or elements in the XML.
Now, let’s create a Nesting class to demonstrate nested XML structures:
Here’s our main class demonstrating XML operations:
This example demonstrates:
Creating Java objects representing XML structures.
Marshalling Java objects to XML using JAXB.
Unmarshalling XML back into Java objects.
Handling nested XML structures.
To run this program, compile it and execute:
The output will show the XML representations of our Java objects and demonstrate the marshalling and unmarshalling processes.
Note that unlike the original example which uses a low-level XML API, this Java version uses JAXB, which provides a higher-level, more object-oriented approach to XML processing. This is more idiomatic in Java applications.