2015-09-26 1538 views
1

如何在下面的情况下选择PriceEventName类属性的属性“name”的值,如果我将@XmlAttribute放在它的上面这是变成一个异常“错误@ XmlAttribute/@ XmlValue需要引用映射在XML文本Java类型” 我看巨资在互联网上,但我没有找到类似的东西,以我的情况@ XmlAttribute/@ XmlValue需要引用映射到XML中的文本的Java类型

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

PriceEventName的Java类定义是什么?属性需要具有诸如String,int,boolean等类型,即只能写成XML属性的类型。可能你可能需要定义一个适配器。 – laune

+0

@peter在这里,我们去我已经添加了类的定义,我可以请你的意见 – poa

+0

你需要使用一个适配器,将一个像“X-mas”这样的字符串映射到PriceEventName,反之亦然。 – laune

回答

1

这是你如何申报外地与适配器的属性:

@XmlJavaTypeAdapter(PenAdapter.class) 
@XmlAttribute 
protected PriceEventName name; 
public PriceEventName getName() { return name; } 
public void setName(PriceEventName value) { this.name = value; } 

添加你需要一个getter添加到PriceEventName:

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(); 
    } 
} 
相关问题