Red Hat Training
A Red Hat training course is available for Red Hat Fuse
36.3. 使用 Unbound 属性
概述
XML Schema 提供了一种机制,允许您在复杂类型定义中保留任意属性的位置。使用这个机制,您可以定义具有任何属性的复杂类型。例如,您可以创建一个定义元素 <robot name="epsilon" />、<robot age="10000" /> 或 <robot type="weevil" /> 的类型,但不指定三个属性。这在需要灵活性时特别有用。
在 XML Schema 中定义
在 XML Schema 中使用 anyAttribute 元素定义 Undeclared 属性。它可在何时使用属性元素。anyAttribute 元素没有属性,如 例 36.7 “带有 Undeclared Attribute 的复杂类型” 所示。
例 36.7. 带有 Undeclared Attribute 的复杂类型
<complexType name="arbitter">
<sequence>
<element name="name" type="xsd:string" />
<element name="rate" type="xsd:float" />
</sequence>
<anyAttribute />
</complexType>
定义的类型(即 arbitter )具有两个元素,它可以具有任意类型的一个属性。例 36.8 “使用 Wild 卡属性定义的 Elements 示例” 中显示的三个元素均可从复杂类型 arbitter 生成。
例 36.8. 使用 Wild 卡属性定义的 Elements 示例
<officer rank="12"><name>...</name><rate>...</rate></officer> <lawyer type="divorce"><name>...</name><rate>...</rate></lawyer> <judge><name>...</name><rate>...</rate></judge>
映射到 Java
当包含 anyAttribute 元素的复杂类型映射到 Java 时,代码生成器会将一个名为 otherAttributes 的成员添加到生成的类。otherAttributes 是 java.util.Map<QName、String > 且具有 getter 方法,它可以返回映射的实时实例。由于从 getter 返回的映射为 live,因此任何对映射的修改都会被自动应用。例 36.9 “带有 Undeclared Attribute 的 complexity Type 的类” 显示为 例 36.7 “带有 Undeclared Attribute 的复杂类型” 中定义的复杂类型生成的类。
例 36.9. 带有 Undeclared Attribute 的 complexity Type 的类
public class Arbitter {
@XmlElement(required = true)
protected String name;
protected float rate;
@XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>();
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public float getRate() {
return rate;
}
public void setRate(float value) {
this.rate = value;
}
public Map<QName, String> getOtherAttributes() { return otherAttributes; }
}使用不正确的属性
生成的类的 otherAttributes 成员需要使用 Map 对象进行填充。该映射使用 QNames 进行键。获取 map 后,您可以访问对象上设置的任何属性,并在对象上设置新属性。
例 36.10 “使用 Undeclared 属性” 显示使用 undeclared 属性的示例代码。
例 36.10. 使用 Undeclared 属性
Arbitter judge = new Arbitter();
Map<QName, String> otherAtts = judge.getOtherAttributes();
QName at1 = new QName("test.apache.org", "house");
QName at2 = new QName("test.apache.org", "veteran");
otherAtts.put(at1, "Cape");
otherAtts.put(at2, "false");
String vetStatus = otherAtts.get(at2);例 36.10 “使用 Undeclared 属性” 中的代码执行以下操作:
获取包含未declared 属性的映射。
创建 QName 以用于属性。
将属性的值设置到映射中。
检索其中一个属性的值。