编组期间未设置 JAXB 固定属性

JAXB Fixed Attribute not set during marshalling

JAXB 似乎无法默认设置固定的属性值。这是预期的行为,还是我做错了什么?

我有一个 xsd 像:

<element name="AccountCategory" type="tns:Integer"></element>
<xs:complexType name="Integer">
    <xs:simpleContent>
        <xs:extension base="xs:int">
            <xs:attribute name="e-dtype" fixed="int"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

编组使用新产品创建的 java 对象:

<AccountCategory>5</AccountCategory>

Java:

com.sample.Integer val = new com.sample.Integer();
val.setValue(5);
parentObject.setAccountCategory(val);

我可以手动设置属性值,而且效果很好。另外,如果我只是将它重置为它自己的值,它也可以工作。似乎编组器在生成 XML?

时没有使用 get 方法
val.setEDtype(val.getEDtype());

结果

<AccountCategory e-dtype="int">5</AccountCategory>

下面生成的.java:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Integer", propOrder = {
    "value"
})
public class Integer {

@XmlValue
protected int value;
@XmlAttribute(name = "e-dtype")
@XmlSchemaType(name = "anySimpleType")
protected String eDtype;

/**
 * Gets the value of the value property.
 * 
 */
public int getValue() {
    return value;
}

/**
 * Sets the value of the value property.
 * 
 */
public void setValue(int value) {
    this.value = value;
}

/**
 * Gets the value of the eDtype property.
 * 
 * @return
 *     possible object is
 *     {@link String }
 *     
 */
public String getEDtype() {
    if (eDtype == null) {
        return "int";
    } else {
        return eDtype;
    }
}

/**
 * Sets the value of the eDtype property.
 * 
 * @param value
 *     allowed object is
 *     {@link String }
 *     
 */
public void setEDtype(String value) {
    this.eDtype = value;
}

引用 XML Schema Part 0 - 2.2.1 Occurrence Constraints:

The fixed attribute is used in both attribute and element declarations to ensure that the attributes and elements are set to particular values. For example, po.xsd contains a declaration for the country attribute, which is declared with a fixed value US. This declaration means that the appearance of a country attribute in an instance document is optional (the default value of use is optional), although if the attribute does appear, its value must be US, and if the attribute does not appear, the schema processor will provide a country attribute with the value US.

因此,如您所见,因为您的属性是 optional,除非您提供一个值,否则不会生成它,但该值必须是 int 才能符合模式。

调用 get 会给你 default/fixed 值,它应该
如果未设置,生成将省略属性,因为它应该

不,编组器没有使用 get 方法,因为 @XmlAccessorTypeXmlAccessType.FIELD

尝试使用 jaxb 绑定 fixedAttributeAsConstantProperty,例如 here

<schema targetNamespace="https://whosebug.com/example" 
        xmlns="http://www.w3.org/2001/XMLSchema" 
        xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        jaxb:version="2.0">
  <annotation>
    <appinfo>
      <jaxb:globalBindings fixedAttributeAsConstantProperty="true" />
    </appinfo>
  </annotation>
  ...
</schema>