java JAXB 解组返回属性的空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7991600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAXB unmarshal returning null values for attributes
提问by satish b
Can you please diagnose why my code prints out [null, null, null, null]:
你能诊断一下为什么我的代码打印出 [null, null, null, null]:
Unmarshaller m = JAXBContext.newInstance(Roles.class).createUnmarshaller();
Roles root = m.ummarshal(new FileReader("test.xml"));
System.out.println(root);
I tried debugging in eclipse but breakpoints at the setters and getters don't hit
我尝试在 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
角色.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;}
}
采纳答案by satish b
I solved the problem myself.
我自己解决了这个问题。
You need to write: @XmlAttribute(name="Id")
& @XmlAttribute(name="Value")
above the getId()
and getValue()
in place of just @XmlAttribute
. The identifier names are not picked up.
你需要写:@XmlAttribute(name="Id")
&@XmlAttribute(name="Value")
在getId()
and之上,而getValue()
不是 just @XmlAttribute
。不选取标识符名称。
回答by Zds
The problem is you are not following Java naming conventions: variables need to start with lowercase letter. If you used lowercase variable and element names, it would work without listing the names explicitly:
问题是您没有遵循 Java 命名约定:变量需要以小写字母开头。如果您使用小写变量和元素名称,则无需明确列出名称即可工作:
@XmlAttribute
private String id;
public String getId() {return id;}
public void setId(String id) {id = id;}
and
和
<?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>