attributeGroup 元素绑定支持

本主题专门介绍一项旧有技术。现在应通过使用以下链接来创建 XML Web 服务和 XML Web 服务客户端: Windows Communication Foundation.

.NET Framework 为 <attributeGroup> 元素提供部分绑定支持。

当从 XML 架构文档生成源代码时,Xsd.exe 会直接将每个 <attributeGroup> 引用扩展为与包含该引用的 <complexType> 定义相对应的类。

说明

<attributeGroup> 元素使架构设计师可以全局定义一个特性组,然后通过引用在任意数目的复杂类型中重用该组。

.NET Framework 没有用于在代码中表示特性组的术语。当从 XML 架构文档生成源代码时,Xsd.exe 会通过 ref 特性将每个 <attributeGroup> 引用直接扩展为与包含该引用的 <complexType> 定义相对应的类。对于每个特性,都生成一个公共字段。出现的每个公共字段都具有 XmlAttributeAttribute 特性,该特性还可以用简略名称 XmlAttribute 来表示。

如果开发人员希望避免直接在多个类中定义同一组与特性绑定的字段或属性,则可以手动创建一个基类,并让那些表示 XML 架构复杂类型的类从这个基类继承。出现的每个公共字段或属性都应当具有 XmlAttribute 特性;否则,它将在复杂类型中被解释为元素,而非特性。

Example

输入 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