[英]JAXB unmarshal list element by element
I need some help with unmarshalling some XML. 我需要一些有关解组XML的帮助。 Especially with unmarshalling a list of elements.
特别是在解组元素列表时。 See the following example:
请参见以下示例:
@XmlRootElement(name="element")
public class Element
{
private ArrayList<Element> children;
public ArrayList<Element> getChildren() {
return children;
}
@XmlElementWrapper(name = "children")
@XmlElement(name = "element")
public void setChildren(ArrayList<Element> children) {
this.children = children;
}
}
This will unmarshal the list perfectly, BUT what I need is an unmarshalling of all children element by element and adding them through some "addElement" method: 这将完美地解组列表,但是我需要的是逐个元素对所有子元素进行解组 ,然后通过“ addElement”方法添加它们:
public void addElement(Element element) {
children.add(element)
}
Is this possible with some simple annotation magic ? 使用一些简单的注释魔术有可能吗? Of course I could loop through the elements and call "addElement".
当然,我可以遍历元素并调用“ addElement”。
You can simply pretend your appender is a setter. 您可以简单地假装您的附加程序是一个setter。
@XmlRootElement(name = "element")
public class Element {
private List<Element> children = new LinkedList<Element>();
@XmlTransient
public List<Element> getChildren() {
return children;
}
@XmlElement(name = "element")
public void setChild(Element child) {
this.children.add(child);
}
private String value;
@XmlAttribute
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
JAXB will invoke the setter every time the element
element is encountered. 每当遇到
element
元素时,JAXB都会调用setter。 This adds the unmarshalled element to the list. 这会将未编组的元素添加到列表中。 The list getter is
@XmlTransient
to avoid handling by JAXB. 列表获取器是
@XmlTransient
以避免被JAXB处理。
Update 更新
I've forgotten to add that this won't work with the @XmlWrapperElement
as it expects a collection property. 我忘了补充一点,因为它期望使用collection属性,所以它
@XmlWrapperElement
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.