这是给出的XML
<AuthentXML>
<Data>
<header>
<asid>AuthenticationSubjectID</asid>
<teid>B6F997AE-FB4E-11D3-80BD-0050DA5DC7B8</teid>
<replyTo>https://r1.authentify.net/s2s/default.asp</replyTo>
</header>
</Data>
</AuthentXML>
这是我的Parser类
public class Test {
public static void main(String args[]) throws Exception {
File file = new File("D:\\Ravi.xml");
JAXBContext jaxbContext = JAXBContext
.newInstance(AuthentifyResult.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
AuthentifyResult authentifyResult = (AuthentifyResult) jaxbUnmarshaller
.unmarshal(file);
System.out.println(authentifyResult.getData().getHeader().getTeid());
}
}
这是AuthentifyResult.java
package com;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="AuthentXML")
public class AuthentifyResult {
private Data data;
@XmlElement(name="Data")
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
这是Data.java
package com;
import javax.xml.bind.annotation.XmlRootElement;
public class Data {
private Header header;
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
}
这是Header.java文件
package com;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
public class Header {
private String ASD;
@XmlAttribute
public String getASD() {
return ASD;
}
public void setASD(String aSD) {
ASD = aSD;
}
@XmlAttribute
public String getTeid() {
return teid;
}
public void setTeid(String teid) {
this.teid = teid;
}
@XmlAttribute
public String getReplyTo() {
return replyTo;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
private String teid;
private String replyTo;
}
我输出为null,我不知道为什么绑定没有发生?
答案 0 :(得分:1)
<Data>
标记使JAXB认为<header>
包含在名为Data
的对象中。您希望将AuthentifyResult
的内容移动到新类,然后让AuthentifyResult
类包含此新元素,其中元素名称为Data
。
@XmlRootElement(name="AuthentXML")
public class AuthentifyResult {
private Data data;
@XmlElement(name="Data")
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
private Header header;
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
}
对于标题类,您希望将@XmlAttribute
注释替换为@XmlElement
。 @XmlAttribute
表示您希望XML看起来像
<header teid="A Value"></header
然而,@XmlElement
暗示您希望您的XML看起来像
<header>
<teid>A Value</teid>
</header>