我使用spring来创建rest-controller,使用jaxb lib来与客户端xml-元素进行交换,因此,我的模型是Users,User和Property。 用户包含用户列表,每个用户包含属性列表。使用用户列表元素创建用户-可以,但是不能为用户元素创建内部属性列表。
我的模特是:
@XmlRootElement(name = "Users")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {
@XmlElement(name = "User")
private List<User> users;
@XmlElement(name = "UserError")
private UserError error;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement(name = "User")
@XmlAccessorType(XmlAccessType.FIELD)
public class User implements Serializable {
@XmlElement(name = "Id")
private String id;
@XmlElement(name = "Name")
private String name;
@XmlElement(name = "Property")
private List<Property> properties;
}
@Getter
@Setter
@NoArgsConstructor
@XmlRootElement(name = "Property")
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class Property implements Serializable {
@XmlElement(name = "passport")
private String passport;
@XmlElement(name = "age")
private String age;
}
如何通过以下方式更改jaxb模型以更改xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User>
<Id>fff</Id>
<Name>Alex</Name>
<Property>
<Name>passport</Name>
<Value>111-222</Value>
</Property>
<Property>
<Name>car</Name>
<Value>bmv</Value>
</Property>
</User>
</Users>
此视图演示
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User>
<Id>fff</Id>
<Name>Alex</Name>
<Properties>
<Property>
<Name>passport</Name>
<Value>111-222</Value>
</Property>
<Property>
<Name>car</Name>
<Value>bmv</Value>
</Property>
</Properties>
</User>
</Users>
答案 0 :(得分:1)
很容易。只需在{的定义中添加@XmlElementWrapper
注释
Java变量properties
:
@XmlElementWrapper(name = "Properties")
@XmlElement(name = "Property")
private List<Property> properties;
这将在<Properties>...</Properties>
个元素的序列周围添加<Property>...</Property>
。