如何在下面的情况下选择一个属性“name”的值,它是一个 PriceEventName 类类型,仅供引用,如果我将 @XmlAttribute 放在它上面,这将导致异常“错误 @XmlAttribute/@XmlValue 需要引用 Java映射到 XML 中的文本的类型”
我在互联网上搜索了很多,但没有找到与我的案例类似的东西
PriceEvent class
package somepackage
import ...
import
@XmlAccessorType(XmlAccessType.FIELD)
public class PriceEvent {
@XmlElement(name="Message",namespace="someValue")
private String color;
private PriceEventName name;// this is an attribute
.
.
}
价格事件名称类
Imports ...
public class PriceEventName {
public static final int PRICEUPDATE_TYPE = 0;
public static final PriceEventName PRICEUPDATE = new PriceEventName(PRICEUPDATE_TYPE, "X-mas");
private static java.util.Hashtable _memberTable = init();
private static java.util.Hashtable init() {
Hashtable members = new Hashtable();
members.put("X-mas", PRICEUPDATE);
return members;
}
private final int type;
private java.lang.String stringValue = null;
public PriceEventName(final int type, final java.lang.String value) {
this.type = type;
this.stringValue = value;
}
public static PriceEventName valueOf(final java.lang.String string) {
java.lang.Object obj = null;
if (string != null) {
obj = _memberTable.get(string);
}
if (obj == null) {
String err = "" + string + " is not a valid PriceEventName";
throw new IllegalArgumentException(err);
}
return (PriceEventName) obj;
}
}
最佳答案
这是您使用适配器将字段声明为属性的方式:
@XmlJavaTypeAdapter(PenAdapter.class)
@XmlAttribute
protected PriceEventName name;
public PriceEventName getName() { return name; }
public void setName(PriceEventName value) { this.name = value; }
添加您需要向 PriceEventName 添加一个 getter:
public String getStringValue(){ return stringValue; }
这是适配器类:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PenAdapter extends XmlAdapter<String,PriceEventName> {
public PriceEventName unmarshal(String v) throws Exception {
return PriceEventName.valueOf( v );
}
public String marshal(PriceEventName v) throws Exception {
return v.getStringValue();
}
}
关于jaxb - @XmlAttribute/@XmlValue 需要引用映射到 XML 文本的 Java 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795648/