我正在尝试使用 JAXB 从此 XML(以上链接)获取数据。我的目标是获取给定地址的纬度和经度。
我已经制作了这些类,但缺少绑定注释。帮助得到这个,在此先感谢
编辑:现在我的代码可以正常工作了,所以我在其答案中粘贴了新代码
public class JAXBExample {
public static void main(String[] args) {
try {
File file = new File("GeoLocation.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(GeocodeResponse.class);//(GeocodeResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
GeocodeResponse latLong = (GeocodeResponse) jaxbUnmarshaller.unmarshal(file);
System.out.println(latLong);
// System.out.println(latLong.getLatitude()+ ", "+latLong.getLongitude());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
@XmlType(propOrder={"latitude","longitude"})
public class Location {
double lat;
double lng;
// @XmlElement(name="lat")
public double getLatitude() {
return lat;
}
// @XmlElement
@XmlElement(name="lat")
public void setLatitude(double latitude) {
this.lat = latitude;
}
// @XmlElement(name="lng")
public double getLongitude() {
return lng;
}
// @XmlAttribute
@XmlElement(name="lng")
public void setLongitude(double longitude) {
this.lng = longitude;
}
}
@XmlType(propOrder={"geometry"})
public class Geometry {
Location aLocation;
// @XmlElement(name="location")
public Location getaLocation() {
return aLocation;
}
@XmlElement(name="location")
public void setaLocation(Location aLocation) {
this.aLocation = aLocation;
}
}
@XmlType(propOrder={"result"})
public class Result {
Geometry aGeometry;
// @XmlElement(name="geometry")
public Geometry getaGeometry() {
return aGeometry;
}
@XmlElement(name="geometry")
public void setaGeometry(Geometry aGeometry) {
this.aGeometry = aGeometry;
}
}
@XmlRootElement
public class GeocodeResponse {
Result aResult;
public Result getaResult() {
return aResult;
}
@XmlElement(name = "result")
public void setaResult(Result aResult) {
this.aResult = aResult;
}
}