JAXB:限定属性禁用默认命名空间xmlns =“”?

时间:2011-07-24 18:50:31

标签: jaxb jaxb2 moxy

当我使用@XmlSchema(attributeFormDefault = XmlNsForm.QUALIFIED, ...)

@XmlAttribute(namespace = "sample.com/y", ...)

JAXB忽略@XmlSchema(namespace = "sample.com/x", ...)

而不是:

<a xmlns="sample.com/y" xmlns:ns0="sample.com/y">
  <b ns0:att=""/>
</a>

生成如下内容:

<ns1:a xmlns:ns1="sample.com/x" xmlns:ns0="sample.com/y">
  <ns1:b ns0:att=""/>
</ns1:a>

这是预期的行为吗?有没有办法纠正这个?

1 个答案:

答案 0 :(得分:4)

EclipseLink JAXB (MOXy) 根据属性表单限定条件处理元素的前缀限定(如下所示)。

命名空间限定没有错,但我同意在可能的情况下使用默认命名空间更好。您可以使用以下错误跟踪此问题的进度:

<强> A

package forum6808921;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class A {

    private String b;

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

}

<强>演示

package forum6808921;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class);

        A a = new A();
        a.setB("Hello World");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(a, System.out);
    }

}

package-info without attributeFormDefault set

@XmlSchema(
        namespace = "sample.com/x"
        , elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
        )
package forum6808921;

import javax.xml.bind.annotation.*;

输出:

<?xml version="1.0" encoding="UTF-8"?>
<a xmlns="sample.com/x">
   <b>Hello World</b>
</a>

package-info with attributeFormDefault set

@XmlSchema(
        namespace = "sample.com/x"
        , elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
        , attributeFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
        )
package forum6808921;

import javax.xml.bind.annotation.*;

输出:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:a xmlns:ns0="sample.com/x">
   <ns0:b>Hello World</ns0:b>
</ns0:a>