Search code examples
javaxml-serializationxml-namespacesxstream

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


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>

Solution

  • Alternatively, this use case could be handled quite easily with a JAXB implementation (Metro, EclipseLink MOXy, Apache JaxMe, etc):

    Domain

    package com.example;
    
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class Domain
    {
        private String type;
        private String os;
    
        @XmlAttribute
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public String getOs() {
            return os;
        }
    
        public void setOs(String os) {
            this.os = os;
        }
    
    }
    

    package-info

    @XmlSchema(xmlns={
            @XmlNs(
                prefix="qemu", 
                namespaceURI="http://libvirt.org/schemas/domain/qemu/1.0")
    })
    package com.example;
    
    import javax.xml.bind.annotation.XmlNs;
    import javax.xml.bind.annotation.XmlSchema;
    

    Demo

    package com.example;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws JAXBException {
            JAXBContext jc = JAXBContext.newInstance(Domain.class);
    
            Domain domain = new Domain();
            domain.setType("kvm");
            domain.setOs("linux");
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(domain, System.out);
        }
    
    
    }
    

    Output

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <domain xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0" type="kvm">
        <os>linux</os>
    </domain>
    

    For More Information