Reputation: 245
As per the title, I have an XML file I need to unmarshal:
<?xml version="1.0"?>
<root>
<wrap>
<Element>something1</Element>
<Element>something2</Element>
<Element>something3</Element>
</wrap>
</root>
"wrap" is simply a wrapper, but the count of "element" varies.
I have two classes to facilitate objects for JAXB:
wrap class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class Wrap {
@XmlElementWrapper(name = "wrap")
@XmlElement(name = "Element")
private List<Element> elementList = new ArrayList<>();
public Wrap() {}
public Wrap(List<Element> list) {
this.elementList = list;
}
public void addElement(Element element) {
this.elementList.add(element);
}
public List<Element> getWrap() {
return this.elementList;
}
public void setWrap(List<Element> wrap) {
this.elementList = wrap;
}
}
element class:
@XmlRootElement(name = "Element")
public class Element {
private String Element;
public Element() {}
public Element(String element) {
this.Element = element;
}
public String getElement() {
return Element;
}
public void setElement(String element) {
this.Element = element;
}
}
Attempting to unmarshal the XML completes without error, however, the element values are not stored with the element objects. Instead toString returns null for each of the objects.
I did populate the objects with some data and marshal them to a file (shown below). This format, of course, is incorrect and should match the XML above.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<wrap>
<Element>
<element>entry1</element>
</Element>
<Element>
<element>entry2</element>
</Element>
<Element>
<element>entry3</element>
</Element>
</wrap>
</root>
I've researched this for awhile now with the assumptions my annotations are incorrect, but perhaps it's something else...
Upvotes: 19
Views: 30981
Reputation: 149047
You need to do the following:
element
property on the Element
class with @XmlValue
.For More Information
Upvotes: 7