Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

How can I use the below code to unmarshal a XML string an map it to the JAXB object below?

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

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

Person person = (Person) unmarshaller.unmarshal("xml string here");

@XmlRootElement(name = "Person")

public class Person {

    @XmlElement(name = "First-Name")

    String firstName;

    @XmlElement(name = "Last-Name")

    String lastName;

    public String getFirstName() {

        return firstName;

    }

    public void setFirstName(String firstName) {

        this.firstName = firstName;

    }

    public String getLastName() {

        return lastName;

    }

    public void setLastName(String lastName) {

        this.lastName = lastName;

    }

}

1 Answer

0 votes
by (46k points)

To pass XML content, you need to wrap the content in a Reader, and unmarshal that instead:

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

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");

Person person = (Person) unmarshaller.unmarshal(reader);

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...