【发布时间】:2017-02-07 00:30:23
【问题描述】:
我正在尝试用 Java 反序列化 XML 的 sn-p:
<anime id="16986">
<info type="Picture" src="http://~.jpg" width="141" height="200">
<img src="http://~" width="141" height="200"/>
<img src="http://~" width="318" height="450"/>
</info>
<info type="Main title" lang="EN">Long Riders!</info>
<info type="Alternative title" lang="JA">ろんぐらいだぁす!</info>
</anime>
我遇到的问题是info 元素可以有一个img 的内联列表,也可以只包含文本。我正在考虑在我的 AnimeHolder 类中将info 视为@Element,但我不能有重复的注释。我还想访问 info 的 lang 属性来检查它是 EN 还是 JP。
我正在使用这些类来保存反序列化的数据:
@Root(name="anime", strict=false)
public class AnimeHolder {
@Attribute(name="id")
private String ANNID;
@ElementList(inline=true)
private List<InfoHolder> infoList;
public String getANNID() {
return ANNID;
}
public List<InfoHolder> getInfoList() {
return infoList;
}
}
对于信息项:
@Root(name="info", strict = false)
public class InfoHolder {
@ElementList(inline=true, required = false)
private List<ImgHolder> imgList;
@Attribute(name = "lang", required = false)
private String language;
public List<ImgHolder> getImgList() {
return imgList;
}
}
【问题讨论】:
-
您可能需要将
<info>定义为具有“混合”内容并在代码中处理文本与<img>元素,例如禁止同时拥有 text 和<img>。请参阅“How to deal with JAXB ComplexType with MixedContent data?”。 -
谢谢!这为我指明了正确的方向。发布我的解决方案。
标签: java xml xml-deserialization simple-framework