JAXB多个@XmlRootElement

时间:2015-08-28 14:37:00

标签: java xml jaxb

我的课程注释如下:

@XmlRootElement(name="response")
@XmlType(propOrder={"paymentid", 
                    "result",
                    "responsecode", 
                    "authorizationcode", 
                    "merchantorderid", 
                    "rrn", 
                    "cardcountry", 
                    "cardtype"})
public class MOTOResponseIn {
...
}

映射XML的根元素旁边也可能是错误响应即可。

如何对类进行注释以便允许两个根元素?

3 个答案:

答案 0 :(得分:4)

在这种情况下,不能使用@XmlRootElement。 你必须使用ObjectFactory。 @XmlElementDecl批注用于表示与命名复杂类型对应的根元素。它放在使用@XmlRegistry注释的类中的工厂方法中(当从XML模式生成时,此类始终称为ObjectFactory)。工厂方法返回包装在JAXBElement实例中的域对象 希望这个网址会有所帮助。

https://dzone.com/articles/jaxb-and-root-elements

答案 1 :(得分:0)

使用单个类和 @XmlRootElement 是不可能的。 但是,如果您不想弄乱 ObjectFactory,为了快速解决,您可以使用抽象类和具体类。 (假设唯一的区别是根元素)

示例:

@XmlAccessorType(XmlAccessType.FIELD)
public abstract class MOTOabstract{
     @XmlAttribute
     private String paymentid;

     @XmlAttribute
     private String result

     @XmlAttribute
     private String responsecode;

     ...
}

@XmlRootElement(name="response")
@XmlAccessorType(XmlAccessType.FIELD)
public class MOTOresponse extends MOTOabstract{}

@XmlRootElement(name="error")
@XmlAccessorType(XmlAccessType.FIELD)
public class MOTOerror extends MOTOabstract{}

答案 2 :(得分:0)

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "id",
        "name",
        "serviceAttrs"
    })
    @XmlSeeAlso({ AddGroup.class, AddGroupRequest.class })
    public class AddGroupAbstract {
    
        @XmlElement(required = true)
        protected String id;
        @XmlElement(required = true)
        protected String name;
        @XmlElement(required = true)
        protected ServiceAttrs serviceAttrs;
    
        ...
    }
    
    @XmlRootElement(name = "addGroup")
    public class AddGroup extends AddGroupAbstract {}
    
    @XmlRootElement(name = "addGroupRequest")
    public class AddGroupRequest extends AddGroupAbstract {}
    
@Endpoint
public class GroupEndpoint {
    private final GroupService groupService;
    private final ServiceService serviceService;
    private final RestTemplate restTemplate;

    public GroupEndpoint(GroupService groupService, ServiceService serviceService, RestTemplate restTemplate) {
        this.groupService = groupService;
        this.serviceService = serviceService;
        this.restTemplate = restTemplate;
    }

    @PayloadRoots({
        @PayloadRoot(namespace = SoapConstants.NAMESPACE_ACCOUNT_URI, localPart = "addGroup"),
        @PayloadRoot(namespace = SoapConstants.NAMESPACE_ACCOUNT_URI, localPart = "addGroupRequest")
    })
    @ResponsePayload
    public AddGroupResponse addGroup(@RequestPayload AddGroupAbstract request) {
        AddGroupResponse response = new AddGroupResponse();

        ...
    }
}