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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6121040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:24:00  来源:igfitidea点击:

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

javaxml-serializationxml-namespacesxstream

提问by Ingo Fischer

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?

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

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 exactlythe following output with XStream?

如何使用 XStream准确实现以下输出?

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

采纳答案by bdoughan

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

或者,可以使用 JAXB 实现(MetroEclipseLink MOXyApache JaxMe等)轻松处理此用例:

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

想要查询更多的信息

回答by dogbane

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

XStream 不支持命名空间,但StaxDriver它使用的支持。您需要将命名空间的详细信息设置为 aQNameMap并将其传递到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>

回答by z0r

This is a bit of a hack, but it's quick and easy: add a field to your class called xmlns, and only have it non-null during serialisation. To continue your example:

这有点小技巧,但它既快捷又简单:向名为 的类添加一个字段xmlns,并且仅在序列化期间将其设为非空。继续你的例子:

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

    private String os;

    (...)

    @XStreamAsAttribute
    @XStreamAlias("xmlns:qemu")
    String xmlns;

    public void serialise(File path) {
        XStream xstream = new XStream(new DomDriver());
        xstream.processAnnotations(Domain.class);
        (...)

        PrintWriter out = new PrintWriter(new FileWriter(path.toFile()));
        xmlns = "http://libvirt.org/schemas/domain/qemu/1.0";
        xstream.toXML(this, out);
        xmlns = null;
    }
}

To be complete, setting xmlns = nullshould be in a finallyclause. Using a PrintWriteralso allows you to insert an XML declaration at the start of the output, if you like.

为了完整起见,设置xmlns = null应该在finally子句中。PrintWriter如果您愿意,还可以使用 a在输出的开头插入 XML 声明。