JAXB解组返回属性的空值

时间:2011-11-03 07:44:07

标签: java xml jaxb

你能否诊断我的代码打印出来的原因[null,null,null,null]:

Unmarshaller m = JAXBContext.newInstance(Roles.class).createUnmarshaller();
Roles root = m.ummarshal(new FileReader("test.xml"));
System.out.println(root);

我尝试在eclipse中进行调试,但是在setter和getter处的断点没有点击

的test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<Roles>
 <Ele Id="1" Value="Yes"/>
 <Ele Id="2" Value="Yes"/>
 <Ele Id="3" Value="No"/>
 <Ele Id="4" Value="Yes"/>
</Roles>

Roles.java

@XmlRootElement(name="Roles")
public class Roles {
 private List<Ele> EleList;
 public Roles() {super();}

 @XmlElement(name="Ele")
 public List<Ele> getEleList() {return EleList;}
 public void setEleList(List<Ele> EleList) {this.EleList = EleList;}
 public String toString() {return EleList.toString();}
}

Ele.java

public class Ele {

 @XmlAttribute
 private String Id;

 @XmlAttribute
 private String Value;

 public Ele(){super();}

 public String getId() {return Id;}
 public void setId(String id) {Id = id;}
 public String getValue() {return Value;}
 public void setValue(String value) {Value = value;}

 public String toString() { if(Id == null || Value == null) return null; else return Id + Value;}
}

2 个答案:

答案 0 :(得分:6)

我自己解决了这个问题。

你需要写:@XmlAttribute(name="Id")&amp;在@XmlAttribute(name="Value")getId()之上getValue()取代@XmlAttribute。标识符名称未被提取。

答案 1 :(得分:1)

问题是您没有遵循Java命名约定:变量需要以小写字母开头。如果您使用了小写变量和元素名称,则可以在不明确列出名称的情况下使用:

@XmlAttribute
private String id;

public String getId() {return id;}
public void setId(String id) {id = id;}

<?xml version="1.0" encoding="UTF-8" ?>
<Roles>
 <Ele id="1" value="Yes"/>
 <Ele id="2" value="Yes"/>
 <Ele id="3" value="No"/>
 <Ele id="4" value="Yes"/>
</Roles>