JAXB解析占用的xml属性

时间:2018-12-18 18:55:23

标签: parsing jaxb

我正在尝试解析xml的以下部分。有两个“位置”标签。第二个已经占有属性。但是我不能正确设置JAXB,第二个类没有设置属性。还有没有一种方法可以使用lombook简化代码,但是将字段保持为私有。

<location>
     <name>London</name>
     <type/>
     <country>GB</country>
     <timezone/>
     <location altitude="0" latitude="51.5085" longitude="-0.1258" geobase="geonames" geobaseid="2643743"/>
</location>

这是外部Location类:

@Data
@XmlRootElement(name = "location")
class Location implements Serializable {
  private String name;
  private String type;
  private String country;
  private String timezone;

  private GeoLocation geoLocation;

  @XmlElement(name = "location")
  public void setGeoLocation(GeoLocation geoLocation) {
      this.geoLocation = geoLocation;
  }
}

第二类:

@Data
@XmlRootElement(name = "location")
class GeoLocation { //Ineer location

  private String _altitude;
  private double _latitude;
  private double _longitude;
  private String _geobase;
  private int _geobaseid;

  @XmlElement(name = "altitude")
  public void set_altitude(String _altitude) {
      this._altitude = _altitude;
  }

  @XmlElement(name = "latitude")
  public void set_latitude(double _latitude) {
      this._latitude = _latitude;
  }

  @XmlElement(name = "longitude")
  public void set_longitude(double _longitude) {
      this._longitude = _longitude;
  }

  @XmlElement(name = "geobase")
  public void set_geobase(String _geobase) {
      this._geobase = _geobase;
  }

  @XmlElement(name = "geobaseid")
  public void set_geobaseid(int _geobaseid) {
      this._geobaseid = _geobaseid;
  }
}

1 个答案:

答案 0 :(得分:0)

 @Data
 @XmlRootElement(name = "location")
 @XmlAccessorType(XmlAccessType.FIELD)
 class Location implements Serializable {
     private String name;
     private String type;
     private String country;
     private String timezone;
     @XmlElement(name = "location")
     private GeoLocation geoLocation;
 }


@Data
@XmlRootElement(name = "location")
@XmlAccessorType(XmlAccessType.FIELD)
class GeoLocation { //Ineer location
  @XmlAttribute(name = "altitude")
  private String _altitude;
  @XmlAttribute(name = "latitude")
  private double _latitude;
  @XmlAttribute(name = "longitude")
  private double _longitude;
  @XmlAttribute(name = "geobase")
  private String _geobase;
  @XmlAttribute(name = "geobaseid")
  private int _geobaseid;
}