我正在 XStream 的帮助下将对象序列化为 XML。
如何告诉 XStream 将 xmlns 插入到对象的 XML 输出中?
例如,我有一个想要序列化的简单对象:
@XStreamAlias(value="domain")
public class Domain
{
@XStreamAsAttribute
private String type;
private String os;
(...)
}
我如何实现exactlyXStream 的以下输出?
<domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
<os>linux</os>
</domain>
XStream 不支持命名空间,但StaxDriver http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/xml/StaxDriver.html它使用,确实。您需要将命名空间的详细信息设置为QNameMap http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/xml/QNameMap.html并将其传递到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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)