Currently I have following output from my program:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<container>
<elements>
<property name="e1">
<foo name="Alex" status="Married"/>
</property>
<property name="e2">
<foo name="Chris" status="Married with 2 children"/>
</property>
</elements>
</container>
As you can see, having both <container>
and <elements>
tags is useless. I'd like to remove <elements>
, so the output would look like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<container>
<property name="e1">
<foo name="Alex" status="Married"/>
</property>
<property name="e2">
<foo name="Chris" status="Married with 2 children"/>
</property>
</container>
Code that's generating first output is listed below:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Container {
@XmlElement
@XmlJavaTypeAdapter(MyAdapter.class)
private Map<String, Foo> elements = new HashMap<String, Foo>();
public Container() {
this.elements = new HashMap<String, Foo>();
}
public Map<String, Foo> getElements() {
return elements;
}
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
@XmlRootElement(name = "foo")
static class Foo {
@XmlAttribute
public String name;
@XmlAttribute
public String status;
public Foo(String name, String status) {
this.name = name;
this.status = status;
}
public Foo() {
}
}
public static void main(String[] args) throws JAXBException {
final JAXBContext context = JAXBContext.newInstance(Container.class);
final Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
final Container c = new Container();
final Map<String, Foo> elementsMap = c.getElements();
elementsMap.put("e1", new Foo("Alex", "Married"));
elementsMap.put("e2", new Foo("Chris", "Married with 2 children"));
m.marshal(c, System.out);
}
}
And MyAdapter
class, based on JAXB @XmlAdapter: Map -> List adapter? (marshall only) :
public class MyAdapter extends XmlAdapter<MyAdapter.AdaptedFoo, Map<String, Foo>> {
static class AdaptedFoo {
public List<Property> property = new ArrayList<>();
}
public static class Property {
@XmlAttribute
public String name;
@XmlElementRef(type = Foo.class)
public Foo value;
}
@Override
public Map<String, Foo> unmarshal(AdaptedFoo v) throws Exception {
return null;
}
@Override
public AdaptedFoo marshal(Map<String, Foo> map) throws Exception {
if (null == map) {
return null;
}
AdaptedFoo adaptedFoo = new AdaptedFoo();
for (Entry<String, Foo> entry : map.entrySet()) {
Property property = new Property();
property.name = entry.getKey();
property.value = entry.getValue();
adaptedFoo.property.add(property);
}
return adaptedFoo;
}
}
How can I remove <elements>
tag from my output?
edit: I've found 'dirty' way to do it - setting @XmlRootElement(name = "")
for Container
class. But is there any 'elegant' way?