java - 编码期间未设置 JAXB 固定属性

标签 java xml xsd jaxb

默认情况下,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才能成为schema合规。

调用 get 将为您提供默认/固定值,它应该
如果未设置,生成将省略属性,它应该

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

关于java - 编码期间未设置 JAXB 固定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031340/

相关文章:

java - 尝试在 Java 中验证 XML 时出错

Java,使用compareTo方法在ToString中按字母顺序打印数组列表

java - 逻辑表达式和中间代码生成

android - 开发高效的布局

android - Android布局文件夹可以包含子文件夹吗?

xml - 如何使用 apache camel 验证 xsd?

java - 为什么 InputStream 和 OutputStream 实现了 Closeable 而 Socket 没有?

java - 具有选择数组中位置的存储过程

xml - Spring 的WebApproot

xml - 未连接到 Internet 时,XML 命名空间如何工作?