Reputation: 1977
I have XML files which contain elements like so:
<element attribute1="a" attribute2="b" attribute3="c">
a b c d e f g
</element>
Is there a way to get both the attributes and also get the value as a list?
I could use @XmlList to get just a list [a, b, c, d, e, f, g], but then I would not have the attributes. I could make a class for the element and use @XmlAttribute and @XmlValue, but then the value would not be as a list.
If there is no way to do this, I will make a class for the element in which a getter method returns the String value as an array or list, and that will be simple enough, but I was just wondering if there is any correct way to have the XML unmarshalled properly in the first place.
Upvotes: 1
Views: 235
Reputation: 149037
The @XmlValue
can be applied to a List
property. With this mapping the list items will be represented as a space separated list in the XML. You can do the following:
Element
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element {
@XmlAttribute
private String attribute1;
@XmlAttribute
private String attribute2;
@XmlAttribute
private String attribute3;
@XmlValue
private List<String> value;
}
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Element.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum17775900/input.xml");
Element element = (Element) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(element, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<element attribute1="a" attribute2="b" attribute3="c">a b c d e f g</element>
Upvotes: 1