我有以下XML:
<mappings>
<mapping>
<parameter attr = "value">asdas</parameter>
<parameter attr = "value2">d123asdsad</parameter>
<parameter attr = "value3">0</parameter>
</mapping>
<mapping>
<parameter attr = "value">23123s</parameter>
<parameter attr = "value2">qwerty</parameter>
<!-- more parameter elements -->
</mapping>
<!-- more mapping elements -->
</mappings>
我有以下java类来映射它:
@XmlRootElement(name = "mappings")
public class Mappings {
@XmlElement(name = "mapping")
private List<Mapping> mMappings;
public List<Mapping> getMappings() {
return mMappings;
}
public void setMappings(List<Mapping> aMappings) {
this.mMappings = aMappings;
}
}
public class Mapping {
@XmlElement(name = "parameter")
private List<Parameter> mParameters;
public List<Parameter> getParameters() {
return mParameters;
}
public void setParameters(List<Parameter> aParameters) {
this.mParameters = aParameters;
}
}
public class Parameter {
@XmlAttribute(name = "attr")
private String mName;
@XmlValue
private String mValue;
public String getName() {
return mName;
}
public void setName(String aName) {
this.mName = aName;
}
public String getValue() {
return mValue;
}
public void setValue(String aValue) {
this.mValue = aValue;
}
}
当我尝试用
解组时JAXBContext context = JAXBContext.newInstance(BundleMappings.class);
Unmarshaller um = context.createUnmarshaller();
mappings = (BundleMappings)um.unmarshal(new File(myFile));
我收到此错误
If a class has @XmlElement property, it cannot have @XmlValue property.
我需要参数同时具有'attr'属性和内容,所以我做错了什么?
答案 0 :(得分:15)
默认情况下JAXB (JSR-222)实现将公共属性(get / set方法)和带注释的字段视为映射(和单独)。默认映射为@XmlElement
,因此您的属性将被视为以这种方式映射。
解决方案#1
由于您要对字段进行注释,因此需要在课程中添加@XmlAccessorType(XmlAccessType.FIELD)
。
@XmlAccessorType(XmlAccessType.FIELD)
public class Parameter {
@XmlAttribute(name = "attr")
private String mName;
@XmlValue
private String mValue;
public String getName() {
return mName;
}
public void setName(String aName) {
this.mName = aName;
}
public String getValue() {
return mValue;
}
public void setValue(String aValue) {
this.mValue = aValue;
}
}
解决方案#2
注释get(或set)方法。
public class Parameter {
private String mName;
private String mValue;
@XmlAttribute(name = "attr")
public String getName() {
return mName;
}
public void setName(String aName) {
this.mName = aName;
}
@XmlValue
public String getValue() {
return mValue;
}
public void setValue(String aValue) {
this.mValue = aValue;
}
}
了解更多信息
<强>更新强>
您还需要使用@XmlElement
属性上的mappings
注释来指定元素名称应为mapping
。
@XmlRootElement(name = "mappings")
public class Mappings {
private List<Mapping> mMappings;
@XmlElement(name="mapping")
public List<Mapping> getMappings() {
return mMappings;
}
public void setMappings(List<Mapping> aMappings) {
this.mMappings = aMappings;
}
}