How to add an XML namespace (xmlns) when serializing an object to XML

Wolkenarchitekt picture Wolkenarchitekt · May 25, 2011 · Viewed 17k times · Source

I'm serializing Objects to XML with the help of XStream. How do I tell XStream to insert an xmlns to the XML output of my object?

As an example, I have this simple object I want to serialize:

@XStreamAlias(value="domain")
public class Domain
{
    @XStreamAsAttribute
    private String type;

    private String os;

    (...)
}

How do I achieve exactly the following output with XStream?

<domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
  <os>linux</os>
</domain>

Answer

dogbane picture dogbane · May 25, 2011

XStream doesn't support namespaces but the StaxDriver it uses, does. You need to set the details of your namespace into a QNameMap and pass that into the StaxDriver:

QNameMap qmap = new QNameMap();
qmap.setDefaultNamespace("http://libvirt.org/schemas/domain/qemu/1.0");
qmap.setDefaultPrefix("qemu");
StaxDriver staxDriver = new StaxDriver(qmap);    
XStream xstream = new XStream(staxDriver);
xstream.autodetectAnnotations(true);
xstream.alias("domain", Domain.class);

Domain d = new Domain("kvm","linux");
String xml = xstream.toXML(d);

Output:

<qemu:domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
  <qemu:os>linux</qemu:os>
</qemu:domain>