默认情况下,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 thecountry
attribute, which is declared with afixed
valueUS
. This declaration means that the appearance of acountry
attribute in an instance document is optional (the default value ofuse
isoptional
), although if the attribute does appear, its value must beUS
, and if the attribute does not appear, the schema processor will provide acountry
attribute with the valueUS
.
所以,正如你所看到的,因为你的属性是optional
,除非你给一个值,否则它不会被生成,但是那个值必须是int
才能成为schema合规。
调用 get
将为您提供默认/固定值,它应该,
如果未设置,生成将省略属性,它应该。
不,编码器没有使用 get
方法,因为 @XmlAccessorType
是 XmlAccessType.FIELD
。
关于java - 编码期间未设置 JAXB 固定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031340/