使用JAXB从XML String创建Object

问题

如何使用以下代码解组XML字符串并将其映射到下面的JAXB对象?

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 热门回答(239 赞)

要传递XML内容,你需要将内容包装在aReader中,然后将其解组:

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

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

#2 热门回答(134 赞)

或者如果你想要一个简单的单行:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

#3 热门回答(20 赞)

没有unmarshal(String)方法。你应该使用aReader

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

但通常你会从某个地方获取该字符串,例如文件。如果是这样的话,最好通过FileReader自己。