使用 JAXB 从 XML 字符串创建对象

2022-08-31 06:36:43

如何使用下面的代码将 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

要传递 XML 内容,您需要将内容包装在 中,并取消元帅,而不是:Reader

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

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

答案 2

或者,如果您想要一个简单的单行代码:

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

推荐