[英]Extract value from list of xml elements with jaxb
我有一個XML文檔,結構像
<thing>
<attr name="one">first</attr>
<attr name="two">second</attr>
<attr name="three">third</attr>
</thing>
我有這樣設置的JAXB類:
public class Thing {
List<Attribute> attr = new ArrayList<Attribute>();
@XmlElement(name="attr")
public List<Attribute> getAttr() { return this.attr; }
public void setAttr(List<Attribute> attr) { this.attr = attr; }
}
public class Attribute {
String value;
String name;
@XmlAttribute
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
@XmlElement
public String getValue() { return this.value;}
public void setValue(String value) { this.value = value; }
}
當我解組文檔時,如果我循環for (Attribute a : thing.getAttr())
進行a.getName()
它將打印“一個”,“兩個”,“三個”,但是a.getValue()
只是空值。
我注釋不正確嗎? 即使將注釋設置為@XmlElement(name="attr")
它似乎也可以執行相同的操作。
這將解決您的問題:
@XmlValue
public String getValue() { return this.value;}
這不是子元素,而是您要查找的當前元素值。
編輯:和順便說一句,您應該在Thing類上添加@XmlRootElement
批注,以防丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.