我正在使用JAXB创建xml。我想在元素PrimaryValue和AlternativeSpelling上设置属性“ lang”。
<AgencyOrUnit>
<PrimaryValue lang="el">ΓΑΔΑ</PrimaryValue>
<AlternativeSpelling lang="en">Athens General Police Directorate</AlternativeSpelling>
</AgencyOrUnit>
这是我的代码:
@XmlRootElement(name = "OwnerReference")
@XmlType(propOrder = { "primaryValue", "alternativeSpelling"})
public class AgencyOrUnit {
private String PrimaryValue;
private String AlternativeSpelling;
public String getPrimaryValue() {
return PrimaryValue;
}
public void setPrimaryValue(String PrimaryValue){
this.PrimaryValue = PrimaryValue;
}
public String getAlternativeSpelling() {
return AlternativeSpelling;
}
public void setAlternativeSpelling(String AlternativeSpelling){
this.AlternativeSpelling = AlternativeSpelling;
}
}
这里是编组过程:
AgencyOrUnit agencyOrUnit = new AgencyOrUnit();
agencyOrUnit.setPrimaryValue("ΓΑΔΑ");
agencyOrUnit.setAlternativeSpelling("General Police");
问题是我不知道如何在元素primaryValue和AlternativeSpelling上设置带有值的属性?
答案 0 :(得分:1)
您可以使用注释@XmlValue
和@XmlAttribute
,但需要创建一个新类来容纳lang
和原始值字符串。像这样:
@Setter
@AllArgsConstructor
public class LocaleString {
private String lang;
private String value;
@XmlAttribute
public String getLang() {
return lang;
}
@XmlValue
public String getValue() {
return value;
}
}
然后相应地修改您的AgencyOrUnit
:
@XmlRootElement(name = "OwnerReference")
@XmlType(propOrder = { "primaryValue", "alternativeSpelling"})
@Getter @Setter
public class AgencyOrUnit {
private LocaleString PrimaryValue;
private LocaleString AlternativeSpelling;
}
测试:
@Test
void test() throws JAXBException {
AgencyOrUnit agencyOrUnit = new AgencyOrUnit();
agencyOrUnit.setPrimaryValue(new LocaleString("el", "ΓΑΔΑ"));
agencyOrUnit.setAlternativeSpelling(new LocaleString("en", "General Police"));
JAXBContext ctx = JAXBContext.newInstance(AgencyOrUnit.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(agencyOrUnit, System.out);
}
,您应该会看到:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OwnerReference>
<primaryValue lang="el">ΓΑΔΑ</primaryValue>
<alternativeSpelling lang="en">General Police</alternativeSpelling>
</OwnerReference>