Java JAXB:我如何注释类以便它们属于不同的命名空间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/870691/
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-08-11 20:28:38  来源:igfitidea点击:

JAXB: How do I annotate classes so that they belong to different namespaces?

javaxmlnamespacesjaxburn

提问by ivan_ivanovich_ivanoff

I want to have JAXB-annotatedclasses which would be marshalled/unmarshalled to different XML namespaces.

我想要有JAXB 注释的类,这些类将被编组/解组到不同的 XML 命名空间

What I need is something like:

我需要的是这样的:

<someRootElement xmlns="urn:my:ns1"
    xmlns:a="urn:my:ns2" xmlns:b="urn:my:ns3">

  <someElement/>
  <a:someElement/>
  <b:someElement/>

</someRootElement>

How can it be done?

怎么做到呢?

Can it be done programatically? (withoutthe need for JAXB's .xjb bindings file?)

可以以编程方式完成吗?(而不需要JAXB的.xjb绑定文件?)

采纳答案by andri

@XmlRootElement(name="someRootElement", namespace = "urn:my:ns1")
class Test {
    @XmlElement(name="someElement", namespace="urn:my:ns1")
    String elem1 = "One";

    @XmlElement(name="someElement", namespace="urn:my:ns2")
    String elem2 = "Two";

    @XmlElement(name="someElement", namespace="urn:my:ns3")
    String elem3 = "Three";
}

This marshals into the following XML:

这将编组为以下 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<someRootElement xmlns="urn:my:ns1" xmlns:ns2="urn:my:ns2" xmlns:ns3="urn:my:ns3">
    <someElement>One</someElement>
    <ns2:someElement>Two</ns2:someElement>
    <ns3:someElement>Three</ns3:someElement>
</someRootElement>

If you are using JAXB RI and don't like the default ns2and ns3namespace prefixes, you need to provide your own NamespacePrefixMapper.

如果您使用 JAXB RI 并且不喜欢默认ns2ns3命名空间前缀,则需要提供您自己的NamespacePrefixMapper.