<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="2" yahoo:created="2016-02-17T21:25:49Z" yahoo:lang="en-US">
<results>
<rate id="USDEUR">
<Name>USD/EUR</Name>
<Rate>0.8990</Rate>
<Date>2/17/2016</Date>
<Time>9:26pm</Time>
<Ask>0.8991</Ask>
<Bid>0.8990</Bid>
</rate>
<rate id="USDUAH">
<Name>USD/UAH</Name>
<Rate>26.9000</Rate>
<Date>2/17/2016</Date>
<Time>9:25pm</Time>
<Ask>27.0000</Ask>
<Bid>26.9000</Bid>
</rate>
</results>
</query>
我试图通过以下代码解析此文档:
@XmlRootElement(name="query")
@XmlAccessorType(XmlAccessType.FIELD)
public class Query {
public List<Rate> rate = new ArrayList<>();
@XmlElement( name = "rate" )
public void setQuery( List rate )
{
this.rate = rate;
}
@Override
public String toString() {
return "Query{" +
"rate=" + rate +
'}';
}
}
/////////////////////////////////////////////////////////////////////////
@XmlRootElement( name = "rate" )
public class Rate {
String id;
@XmlElement( name = "id" )
public void setId(String id){
this.id = id;
}
String rate;
@XmlElement( name = "rate" )
public void setRate(String rate){
this.rate = rate;
}
}
//////////////////////////////////////////////
File file = new File("E://xml//2.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Query.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Query mu = (Query) jaxbUnmarshaller.unmarshal(file);
System.out.println(mu);
它有什么问题? 三次重写类,停止在这个变种上
在控制台中:Query{rate=[]}
ArrayList
评价与文档中的节点无关
//虚拟文字
答案 0 :(得分:0)
你的课程错了。
<强> Query.java 强>
@XmlRootElement(name="query")
@XmlAccessorType(XmlAccessType.FIELD)
public class Query {
@XmlElementWrapper
@XmlElement(name="rate")
private List<Rate> results;
public List<Rate> getRate() {
return results;
}
public void setRate(List<Rate> rate) {
this.results = rate;
}
}
<强> Rate.java 强>
@XmlRootElement( name = "rate" )
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rate", propOrder = {
"rate"
})
public class Rate {
@XmlAttribute(name="id")
private String id;
@XmlElement(name="Rate")
private String rate;
public String getId() {
return id;
}
public void setId(String id){
this.id = id;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}