JavaJAXB:如何从嵌套元素中检索文本属性?
我希望Country类存储“ISO_3166-1_Alpha-2_代码”。代码当前返回“ISO_3166-1_数字-3_代码”。不知道如何调整Country类以获得我想要的特定属性
XML:
<?xml version='1.0' encoding='UTF-8'?>
<wd:Message_Event_Configuration">
<wd:Message_Event_Configuration_Data>
<wd:Country_Reference wd:Descriptor="Saint Martin">
<wd:ID wd:type="WID">66b7082a21e510000961bb6d82b5002a</wd:ID>
<wd:ID wd:type="ISO_3166-1_Alpha-2_Code">MF</wd:ID>
<wd:ID wd:type="ISO_3166-1_Alpha-3_Code">MAF</wd:ID>
<wd:ID wd:type="ISO_3166-1_Numeric-3_Code">663</wd:ID>
</wd:Country_Reference>
<wd:Country_Reference wd:Descriptor="Saint Barthelemy">
<wd:ID wd:type="WID">881527f6cec910000ba81e8dccf61127</wd:ID>
<wd:ID wd:type="ISO_3166-1_Alpha-2_Code">BL</wd:ID>
<wd:ID wd:type="ISO_3166-1_Alpha-3_Code">BLM</wd:ID>
<wd:ID wd:type="ISO_3166-1_Numeric-3_Code">652</wd:ID>
</wd:Country_Reference>
</wd:Message_Event_Configuration_Data>
</wd:Message_Event_Configuration>
国家名单:
@XmlRootElement(name = "Message_Event_Configuration")
@XmlAccessorType(XmlAccessType.FIELD)
public class Countries {
@XmlElementWrapper(name = "Message_Event_Configuration_Data")
@XmlElement(name = "Country_Reference")
private List<Country> countries = new ArrayList<Country>();
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
国家:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Country_Reference")
public class Country {
@XmlElement(name = "ID")
private String isoCode;
public Country() {
}
public Country(String isoCode) {
this.isoCode = isoCode;
}
@XmlAttribute(name = "ISO_3166-1_Alpha-2_Code")
public String getISOCode() {
return isoCode;
}
public void setISOCode(String isoCode) {
this.isoCode = isoCode;
}
}
# 1 楼答案
<Country_Reference>
XML元素以一种相当简单的形式包含ISO代码 在几个<wd:ID>
XML元素中使用复杂的方法。 因此,将它们建模为JavaString
属性太简单了相反,您需要对Java结构进行建模,使其与XML结构更为相似
XML元素序列} 注释
<wd:ID>
可以由属性List<ID> idList
建模 需要用^{XML属性} 注释
wd:Descriptor="...."
可以由属性String descriptor
建模 需要用^{为了方便起见,您可以添加一个all arguments构造函数和一些获取 来自
List<ID>
的WID和ISO代码XML元素
<wd:ID>
非常复杂。因此,我们需要一个单独的POJO类来对它们进行建模。 让我们调用类ID
<wd:ID ..>
和</wd:ID>
之间的XML文本由属性String value
建模 需要用^{XML属性} 注释
wd:type="..."
由属性String type
建模 需要用^{为了方便上面的类
Country
使用,添加了一个all arguments构造函数下面的屏幕截图(取自调试器)显示了Java结构 并确认XML示例的解组工作正常: