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...
public List<T> Unmarshal(List<Entry> entries, Class clazz) { List<T> out = new ArrayList<T>(); T instance; for (Entry e : entries) { try { JAXBContext context = JAXBContext. newInstance(clazz); Unmarshaller unmarsh = context.
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
The Unmarshaller class governs the process of deserializing XML data into newly created Java content trees, optionally validating the XML data as it is unmarshalled. It provides an overloading of unmarshal methods for many different input kinds.
You need to do the following:
element
property on the Element
class with @XmlValue
.For More Information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With