.NET Framework 为 <attributeGroup> 元素提供部分绑定支持。
当从 XML 架构文档生成源代码时,Xsd.exe 会直接将每个 <attributeGroup> 引用扩展为与包含该引用的 <complexType> 定义相对应的类。
说明
<attributeGroup> 元素使架构设计师可以全局定义一个属性组,然后通过引用在任意数目的复杂类型中重用该组。
.NET Framework 没有用于在代码中表示属性组的术语。 当从 XML 架构文档生成源代码时,Xsd.exe 会通过 ref 属性将每个 <attributeGroup> 引用直接扩展为与包含该引用的 <complexType> 定义相对应的类。 对于每个属性,都生成一个公共字段。 出现的每个公共字段都具有 XmlAttributeAttribute 属性,该属性还可以用简略名称 XmlAttribute 来表示。
如果开发人员希望避免直接在多个类中定义同一组与属性 (Attribute) 绑定的字段或属性 (Property),则可以手动创建一个基类,并让那些表示 XML 架构复杂类型的类从这个基类继承。 出现的每个公共字段或属性都应当具有 XmlAttribute 属性;否则,它将在复杂类型中被解释为元素,而非属性。
示例
输入 XML 架构文档:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://example.org/" targetNamespace="http://example.org/" elementFormDefault="qualified">
<xsd:attributeGroup name="version">
<xsd:attribute name="changeNumber" type="xsd:int" use="required"/>
<xsd:attribute name="instanceId" type="xsd:string" use="required"/>
</xsd:attributeGroup>
<xsd:complexType name="keyInfo">
<xsd:sequence>
<xsd:element name="key" type="xsd:string"/>
</xsd:sequence>
<xsd:attributeGroup ref="version" />
</xsd:complexType>
<xsd:element name="key" type="keyInfo"/>
</xsd:schema>
基于前面的 XML 架构文档生成的 C# 类:
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://example.org/")]
[System.Xml.Serialization.XmlRootAttribute("key", Namespace="http://example.org/", IsNullable=false)]
public class keyInfo {
public string key;
[System.Xml.Serialization.XmlAttributeAttribute()]
public int changeNumber;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string instanceId;
}
基于通过前面的 C# 源代码编译得到的程序集生成的 XML 架构复杂类型:
<xs:schema xmlns:tns="http://example.org/" elementFormDefault="qualified" targetNamespace="http://example.org/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="key" type="tns:keyInfo" />
<xs:complexType name="keyInfo">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="key" type="xs:string" />
</xs:sequence>
<xs:attribute name="changeNumber" type="xs:int" />
<xs:attribute name="instanceId" type="xs:string" />
</xs:complexType>
</xs:schema>
可能的属性 | 绑定支持 |
---|---|
id |
Xsd.exe 实用工具会忽略旨在提供唯一标识符的 id 属性。 |
name |
由于 Xsd.exe 实用工具以匿名方式扩展 <attributeGroup> 元素的内容,因此该属性组的名称会被忽略。 请参见 name 属性绑定支持 属性。 |
ref |
.NET Framework 没有用于在代码中表示属性组的术语。 当从 XML 架构文档生成源代码时,Xsd.exe 会将每个 ref 属性对全局声明的属性组的 <attributeGroup> 引用直接扩展为与包含该引用的 <complexType> 定义相对应的类。 对于 <attributeGroup> 中的每个属性,都将生成一个具有 System.Xml.Serialization.XmlAttributeAttribute 属性(还可以用简略名称 XmlAttribute 来表示)的公共字段。 |
可能的父元素:<attributeGroup>、<complexType>、<extension>、<redefine>、<restriction>、<schema>
可能的子元素:<annotation>、<anyAttribute>、<attribute>、<attributeGroup>
请参见
参考
XmlSchemaAttributeGroup
XmlSchemaAttributeGroupRef
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。