在将对象序列化为XML时如何添加XML命名空间(xmlns)

Ing*_*her 9 java xstream xml-serialization xml-namespaces

我在XStream的帮助下将对象序列化为XML.如何告诉XStream将xmlns插入到对象的XML输出中?

作为一个例子,我有这个我要序列化的简单对象:

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

    private String os;

    (...)
}
Run Code Online (Sandbox Code Playgroud)

如何使用XStream 完全实现以下输出?

<domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
  <os>linux</os>
</domain>
Run Code Online (Sandbox Code Playgroud)

dog*_*ane 16

XStream不支持名称空间,但StaxDriver它使用的是名称空间.您需要将命名空间的详细信息设置为a QNameMap并将其传递到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);
Run Code Online (Sandbox Code Playgroud)

输出:

<qemu:domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
  <qemu:os>linux</qemu:os>
</qemu:domain>
Run Code Online (Sandbox Code Playgroud)


bdo*_*han 5

或者,使用JAXB实现(Metro,EclipseLink MOXy,Apache JaxMe等)可以非常轻松地处理这个用例:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

包信息

@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;
Run Code Online (Sandbox Code Playgroud)

演示

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);
    }


}
Run Code Online (Sandbox Code Playgroud)

产量

<?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>
Run Code Online (Sandbox Code Playgroud)

欲获得更多信息