我有以下JAXB实体:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = EntityConstants.PARTNER)
public class FilePartner
{
@XmlAttribute(name = EntityConstants.IDENTIFIER, required = true)
private String identifier;
@XmlElement(name = EntityConstants.NAME)
private String name;
@XmlElement(name = EntityConstants.ROOT_PATH)
private String rootPath;
...
}
序列化为类似的结构:
<file-partner identifier="foo">
<name>bar</name>
<root-path>path123</root-path>
...
</file-partner>
我还有一个代表合作伙伴名单的实体:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = EntityConstants.PARTNERS)
public class FilePartnerList
{
@XmlElement(name = EntityConstants.PARTNER)
private List<FilePartner> partners = new ArrayList<FilePartner>();
public List<FilePartner> getPartners()
{
return partners;
}
public void addPartners(List<FilePartner> partners)
{
this.partners.addAll(partners);
}
}
序列化为:
<partners>
<file-partner identifier="foo">
...
</file-partner>
<file-partner identifier="foo2">
...
</file-partner>
...
</partners>
我正在寻找一种方法来强制jaxb unmarshaller以
的形式反序列化XML<file-partner identifier="foo">
<name>bar</name>
<root-path>path123</root-path>
...
</file-partner>
到列表大小为1的FilePartnerList实例中,即:
JAXBContext context = JAXBContext.newInstance(FilePartner.class, FilePartnerList.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
InputStream inputStream = getResourceAsStream(filePartnerAsXml);
FilePartnerList partnerList = (FilePartnerList) unmarshaller.unmarshal(inputStream); // This SHOULD be unmarshalled to FilePartnerList instead of FilePartner
assertTrue(partnerList.getPartners().getSize().equals(1));
我如何实现这一目标?
答案 0 :(得分:0)
private List<FilePartner> partners = new ArrayList<FilePartner>(**1**);
这样你就可以获得一个固定大小的输入数组......
但我确定你会想要使用&#39; maxocurrs = 1&#39;来获得该模型的XSD。所以你将手动修改XSD。
无论如何:为什么不这样做,如果列表大小必须固定为&#39; 1&#39;,只需将其设置为具有单个孩子的简单节点?像这样(未经测试):
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = EntityConstants.PARTNERS)
public class FilePartnerList
{
@XmlElement(name = EntityConstants.PARTNER)
private FilePartner partners;
public FilePartner getFilePartner()
{
return partner;
}
public void setPartner(FilePartner partner)
{
this.partner = partner;
}
}
这样,每个parnets列表中只有一个合作伙伴。
将服务的XSD与文本和文本相匹配的XML与最大大小为1的节点和节点无法区分。