[英]How to implement parent object attributes (props & values) for children objects during JAXB XML unmarshalling
我有XML配置,我必須用JAXB解組,然后在java代碼中使用這些對象。 我有一個父對象“tags”和兩個子標簽“innerTag”。 所有標簽都有屬性。 輸入配置是:
...
<tags attribute1="value1" attribute2="value2">
<innerTag attribute3="value3"/>
<innerTag attribute4="value4"/>
</tags>
...
我的任務是在解編后實現innerTags的attribute1和attribute2。 它必須像這樣的xml解組:
...
<tags>
<innerTag attribute1="value1" attribute2="value2" attribute3="value3"/>
<innerTag attribute1="value1" attribute2="value2" attribute4="value4"/>
</tags>
...
我在解析XML之后創建了代表對象的類:
@XmlRootElement
class Tags {
private ArrayList<InnerTag> innerTags = new ArrayList<>();
private String attribute1;
private String attribute2;
...
@XmlElement(name = "innerTag")
@XmlElementWrapper(name="tags")
public ArrayList<InnerTag> getInnerTags(){
return innerTags;
}
...
@XmlAttribute
public String getAttribute1(){
return attribute1;
}
@XmlAttribute
public String getAttribute2(){
return attribute2;
}
...
}
而InnerTag類:
@XmlRootElement
class InnerTag {
private String attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
...
@XmlAttribute
public String getAttribute1(){
return attribute1;
}
@XmlAttribute
public String getAttribute2(){
return attribute2;
}
...
@XmlAttribute
public String getAttribute3(){
return attribute3;
}
@XmlAttribute
public String getAttribute4(){
return attribute4;
}
}
我不知道如何為子節點實現父屬性的屬性和值...我沒有找到這樣的JAXB derective,讓我做這樣的屬性實現。 求助,請解決這個問題!
試試這個,
首先解組Tags
對象
File file = new File("XMLFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Tags.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tags tags = (Tags) jaxbUnmarshaller.unmarshal(file);
然后,設置為InnerTag
的tags
屬性(attribute1和attribute2)值
for (int i = 0; i < tags.getInnerTags().size(); i++) {
tags.getInnerTags().get(i).setAttribute1(tags.getAttribute1());
tags.getInnerTags().get(i).setAttribute2(tags.getAttribute2());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.