在将对象序列化为XML时如何添加XML命名空间(xmlns) [英] How to add an XML namespace (xmlns) when serializing an object to XML
本文介绍了在将对象序列化为XML时如何添加XML命名空间(xmlns)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在XStream的帮助下将对象序列化为XML。
如何告诉XStream将xmlns插入到对象的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;
(...)
}
我如何用XStream实现完全以下输出?
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>
推荐答案
或者,这个用例可以很容易地处理JAXB实现( Metro , EclipseLink MOXy , Apache JaxMe 等):
Alternatively, this use case could be handled quite easily with a JAXB implementation (Metro, EclipseLink MOXy, Apache JaxMe, etc):
域
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;
演示
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);
}
}
输出
<?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>
更多信息
- http://bdoughan.blogspot。 com / 2010/08 / jaxb-namespaces.html
- http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-xstream.html
- http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html
- http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-xstream.html
这篇关于在将对象序列化为XML时如何添加XML命名空间(xmlns)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文