@ XmlAttribute / @ XmlValue需要引用映射到XML文本的Java类型

时间:2015-09-26 09:30:52

标签: jaxb unmarshalling xml-attribute

如何选择属性的值' name'这是一个PriceEventName类类型,在下面的例子中,如果我把@XmlAttribute放在它上面,那么结果是异常"错误@XmlAttribute / @XmlValue需要引用映射到XML中的文本的Java类型&# 34; 我在互联网上看得很重,但我没有找到类似于我案例的东西

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 
        .
        .
    }

PriceEventName类

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;
        }
}

1 个答案:

答案 0 :(得分:1)

这是使用适配器将字段声明为属性的方法:

@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();
    }
}