Xml Attribute to Pojo class in Java

 To convert the given XML to a Java POJO class using JAXB, you need to create the `Address` class representing the `<Address>` element and its attributes.


Here's how you can do it:


1. Create the `Address` class for the `<Address>` element:


import javax.xml.bind.annotation.XmlAttribute;

import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement(name = "Address")

public class Address {

    private String street;

    private String city;

    private String zipcode;


    @XmlAttribute

    public String getStreet() {

        return street;

    }


    public void setStreet(String street) {

        this.street = street;

    }


    @XmlAttribute

    public String getCity() {

        return city;

    }


    public void setCity(String city) {

        this.city = city;

    }


    @XmlAttribute

    public String getZipcode() {

        return zipcode;

    }


    public void setZipcode(String zipcode) {

        this.zipcode = zipcode;

    }

}


2. Now, you can unmarshal the XML into the `Address` object:


import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

import java.io.StringReader;


public class XmlToPojoMapper {


    public static void main(String[] args) {

        String xmlData = "<Address street=\"adr1\" city=\"cty1\" zipcode=\"01\"></Address>";


        try {

            // Create JAXBContext and Unmarshaller

            JAXBContext jaxbContext = JAXBContext.newInstance(Address.class);

            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();


            // Unmarshal the XML data into Java object

            Address addressObject = (Address) unmarshaller.unmarshal(new StringReader(xmlData));


            // Now you can work with the Java object

            System.out.println("Street: " + addressObject.getStreet());

            System.out.println("City: " + addressObject.getCity());

            System.out.println("Zipcode: " + addressObject.getZipcode());

        } catch (JAXBException e) {

            e.printStackTrace();

        }

    }

}


When you run the `XmlToPojoMapper` class, it will unmarshal the XML data and populate the `Address` object with the corresponding attribute values. The output will be:


```

Street: adr1

City: cty1

Zipcode: 01

```


With this setup, you have successfully converted the given XML into a POJO class using JAXB. Make sure the XML data is well-formed and has the correct structure for proper unmarshalling.

Post a Comment

0 Comments