我有以下XML:
<;映射>;
<;测绘>;
<;参数attr=“value”>;asdas</参数>;
<;参数attr=“value2”>;d123asdsad</参数>;
<;参数attr=“value3”>;0</参数>;
</测绘>;
<;测绘>;
<;参数attr=“value”>;23123s</参数>;
<;参数attr=“value2”>;qwerty</参数>;
<;!--更多参数元素-->;
</测绘>;
<;!--更多映射元素-->;
</映射>;
我要将它映射到以下java类:
@XmlRootElement(name=“mappings”)
公共类映射{
@xmlement(name=“映射”)
私有列表<;映射>;映射;
公共列表<;映射>;getMappings(){
归还文件;
}
公共void集合映射(列出映射){
this.mMappings=aMappings;
}
}
公共类映射{
@xmlement(name=“parameter”)
私有列表<;参数>;MPParameters;
公共列表<;参数>;获取参数(){
返回参数;
}
公共void setParameters(列出参数){
this.mparemeters=a参数;
}
}
公共类参数{
@XmlAttribute(name=“attr”)
私有字符串mName;
@XmlValue
私有字符串值;
公共字符串getName(){
返回mName;
}
public void setName(字符串名称){
this.mName=aName;
}
公共字符串getValue(){
返回mValue;
}
公共void setValue(字符串aValue){
this.mValue=aValue;
}
}
当我试图解开它的时候
JAXBContext context=JAXBContext.newInstance(BundleMappings.class);
Unmarshaller um=context.createUnmarshaller();
mappings=(BundleMappings)um.unmarshal(新文件(myFile));
我得到这个错误
如果类具有@XmlElement属性,则它不能具有@XmlValue属性。
我需要参数同时具有’attr’属性和内容,那么我做错了什么
默认情况下,强> JAXB(JSR-222)实现考虑公共属性(get /set方法)和注释字段映射(和分离)。默认映射是@xmlement
,因此您的属性将被视为以这种方式映射
解决方案#1
由于您正在注释需要在类中添加@xmlacessortype(xmlacesstype.FIELD)
的字段
@xmlacessortype(xmlacesstype.FIELD)
公共类参数{
@XmlAttribute(name=“attr”)
私有字符串mName;
@XmlValue
私有字符串值;
公共字符串getName(){
返回mName;
}
public void setName(字符串名称){
this.mName=aName;
}
公共字符串getValue(){
返回mValue;
}
公共void setValue(字符串aValue){
this.mValue=aValue;
}
}
解决方案#2
注释get(或set)方法
公共类参数{
私有字符串mName;
私有字符串值;
@XmlAttribute(name=“attr”)
公共字符串getName(){
返回mName;
}
public void setName(字符串名称){
this.mName=aName;
}
@XmlValue
公共字符串getValue(){
返回mValue;
}
公共void setValue(字符串aValue){
this.mValue=aValue;
}
}
了解更多信息
- http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
- http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html
更新
您还需要使用mappings
属性上的@xmlement
注释来指定元素名称应为mapping
@XmlRootElement(name=“mappings”)
公共类映射{
私有列表<;映射>;映射;
@xmlement(name=“映射”)
公共列表<;映射>;getMappings(){
归还文件;
}
公共void集合映射(列出映射){
this.mMappings=aMappings;
}
}