如何将 xml 元素绑定到对象成员变量中?

2022-01-19 00:00:00 xml java jaxb unmarshalling moxy

我正在尝试使用 moxy 将 xml 解组为对象.下面是 xml 的示例.

I'm trying to unmarshal an xml to an object using moxy.Below is the sample of the xml.

<root>
    <name>
        <firstname>value</firstname>
    </name> 
    <address>value of address</address>
</root>

下面是我要映射的类.

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)

public class Response {
  @XmlPath("name/firstname/text()")
  String name;
  Address address;
}

class Address {
  String addressline;
}

现在如何获取 XML 中地址标记的值并将其绑定到类地址的地址线变量.

Now how do I get the values of the address tag in XML and bind it to the addressline variable of class Address.

推荐答案

您需要在 addressline 属性上使用 @XmlValue 注释.

You need to use the @XmlValue annotation on the addressline property.

@XmlAccessorType(XmlAccessType.FIELD)
class Address {
    @XmlValue
    String addressline;
}

相关文章