System.Xml.Serialization.XmlAttributeAttribute Class

Assembly: System.Xml.dll
Namespace: System.Xml.Serialization
Summary
Specifies that the XmlSerializer should serialize the class member as an XML attribute.
C# Syntax:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlAttributeAttribute : Attribute
Remarks
The XmlAttributeAttribute belongs to a family of attributes that controls how the XmlSerializer serializes, or deserializes, an object. For a complete list of similar attributes, see the conceptual topic at MSDN: attributesthatcontrolserialization.

When applied to a public field or property, the XmlAttributeAttribute informs the XmlSerializer to serialize the member as an XML attribute. By default, the XmlSerializer serializes public fields and properties as XML elements.

You can assign the XmlAttributeAttribute to public fields or public (read/write) properties that return a value that is mapped to an XSD simpleType, including all primitive types, byte arrays, and enumerations.

There are two special attributes that can be set with the XmlAttributeAttribute: the xml:lang (specifies language) and xml:space (specifies how to handle white space) attributes. These attributes are intended to convey information that is relevant only to an application processing the XML. Examples of setting these are shown in the following code:

          [XmlAttribute("xml:lang")]
          public string Lang;
          [XmlAttribute("space", 
          Namespace = "http://www.w3.org/XML/1998/namespace")]
          public string Space // Set to default or preserve
          [Visual Basic]
          <XmlAttribute("xml:lang")> _
          Public Lang As String 
          <XmlAttribute("space", _
          Namespace:= "http://www.w3.org/XML/1998/namespace")> _
          Public Space As String ' Set to default or preserve
        

For more information about using attributes, see the conceptual topic at MSDN: extendingmetadatausingattributes.



Note In your code, you can use the word XmlAttribute instead of the longer XmlAttributeAttribute.
Example
The following example serializes a class that contains several fields to which the XmlAttributeAttribute is applied.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;

public class Group
{
   [XmlAttribute (Namespace = "http://www.cpandl.com")]
   public string GroupName;
   
   [XmlAttribute(DataType = "base64Binary")]
   public Byte [] GroupNumber;

   [XmlAttribute(DataType = "date", AttributeName = "CreationDate")]
   public DateTime Today;
}


 
public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("Attributes.xml");
   }


   public void SerializeObject(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer mySerializer =  
      new XmlSerializer(typeof(Group));

      // Writing the file requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);

      // Create an instance of the class that will be serialized.
      Group myGroup = new Group();

      // Set the object properties.
      myGroup.GroupName = ".NET";

      Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
      Convert.ToByte(50)};
      myGroup.GroupNumber = hexByte;

      DateTime myDate = new DateTime(2001,1,10);
      myGroup.Today = myDate;

      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup);
       writer.Close();
   }
}
   

    
See also:
System.Xml.Serialization Namespace

System.Xml.Serialization.XmlAttributeAttribute Member List:

Public Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the XmlAttributeAttribute class.
ctor #2 Overloaded:
.ctor(string attributeName)

Initializes a new instance of the XmlAttributeAttribute class and specifies the name of the generated XML attribute.
ctor #3 Overloaded:
.ctor(Type type)

Initializes a new instance of the XmlAttributeAttribute class.
ctor #4 Overloaded:
.ctor(string attributeName, Type type)

Initializes a new instance of the XmlAttributeAttribute class.
Public Properties
AttributeName Read-write

Gets or sets the name of the XML attribute.
DataType Read-write

Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
Form Read-write

Gets or sets a value indicating whether the XML attribute name generated by the XmlSerializer is qualified.
Namespace Read-write

Gets or sets the XML namespace of the XML attribute.
Type Read-write

Gets or sets the complex type of the XML attribute.
TypeId
(inherited from System.Attribute)
Read-only

See base class member description: System.Attribute.TypeId


When implemented in a derived class, gets a unique identifier for this Attribute.
Public Methods
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetHashCode
(inherited from System.Attribute)
See base class member description: System.Attribute.GetHashCode


Returns the hash code for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
IsDefaultAttribute
(inherited from System.Attribute)
See base class member description: System.Attribute.IsDefaultAttribute


When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match
(inherited from System.Attribute)
See base class member description: System.Attribute.Match


When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.Serialization.XmlAttributeAttribute Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the XmlAttributeAttribute class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlAttributeAttribute();
Example
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class Student
{
   public string StudentName;
   public int StudentNumber;
}
 
public class Book
{
   public string BookName;
   public int BookNumber;
}
public class XMLAttributeAttribute_ctr1
{
   public static void Main()
   {
      XMLAttributeAttribute_ctr1 myAttribute = 
                                 new XMLAttributeAttribute_ctr1();
      myAttribute.SerializeObject("Student.xml","Book.xml");
   }
 
   public void SerializeObject(string studentFilename,string bookFilename)
   {
      XmlSerializer mySerializer;
      TextWriter writer;

      // Create the XmlAttributeOverrides and XmlAttributes objects.
      XmlAttributeOverrides myXmlAttributeOverrides = 
                                                     new XmlAttributeOverrides();
      XmlAttributes myXmlAttributes = new XmlAttributes();

      /* Create an XmlAttributeAttribute set it to 
      the XmlAttribute property of the XmlAttributes object.*/
      XmlAttributeAttribute myXmlAttributeAttribute = 
                                                new XmlAttributeAttribute();
      myXmlAttributeAttribute.AttributeName="Name";
      myXmlAttributes.XmlAttribute = myXmlAttributeAttribute;
      
      
      // Add to the XmlAttributeOverrides. Specify the member name.
      myXmlAttributeOverrides.Add(typeof(Student), "StudentName", 
                                                      myXmlAttributes);

      // Create the XmlSerializer.
      mySerializer = new  XmlSerializer(typeof(Student), 
                                                myXmlAttributeOverrides);
      
      writer = new StreamWriter(studentFilename);

      // Create an instance of the class that will be serialized.
      Student myStudent = new Student();

      // Set the Name property, which will be generated as an XML attribute. 
      myStudent.StudentName= "James";
      myStudent.StudentNumber=1;
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myStudent);
      writer.Close();

      // Create the XmlAttributeOverrides and XmlAttributes objects.
      XmlAttributeOverrides myXmlBookAttributeOverrides = 
                                                new XmlAttributeOverrides();
      XmlAttributes myXmlBookAttributes = new XmlAttributes();

      /* Create an XmlAttributeAttribute set it to 
      the XmlAttribute property of the XmlAttributes object.*/
      XmlAttributeAttribute myXmlBookAttributeAttribute = 
                                           new XmlAttributeAttribute("Name");
      myXmlBookAttributes.XmlAttribute = myXmlBookAttributeAttribute;
      
      
      // Add to the XmlAttributeOverrides. Specify the member name.
      myXmlBookAttributeOverrides.Add(typeof(Book), "BookName", 
                                             myXmlBookAttributes);

      // Create the XmlSerializer.
      mySerializer = new  XmlSerializer(typeof(Book), 
                                       myXmlBookAttributeOverrides);
      
      writer = new StreamWriter(bookFilename);

      // Create an instance of the class that will be serialized.
      Book myBook = new Book();

      // Set the Name property, which will be generated as an XML attribute. 
      myBook.BookName= ".NET";
      myBook.BookNumber=10;
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myBook);
      writer.Close();

   }
}

    

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the XmlAttributeAttribute class and specifies the name of the generated XML attribute.
C# Syntax:
public XmlAttributeAttribute(
   string attributeName
);
Parameters:

attributeName

The name of the XML attribute that the XmlSerializer generates.

Example
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized.
public class Student
{
   public string StudentName;
   public int StudentNumber;
}
 
public class Book
{
   public string BookName;
   public int BookNumber;
}
public class XMLAttributeAttribute_ctr1
{
   public static void Main()
   {
      XMLAttributeAttribute_ctr1 myAttribute = 
                                 new XMLAttributeAttribute_ctr1();
      myAttribute.SerializeObject("Student.xml","Book.xml");
   }
 
   public void SerializeObject(string studentFilename,string bookFilename)
   {
      XmlSerializer mySerializer;
      TextWriter writer;

      // Create the XmlAttributeOverrides and XmlAttributes objects.
      XmlAttributeOverrides myXmlAttributeOverrides = 
                                                     new XmlAttributeOverrides();
      XmlAttributes myXmlAttributes = new XmlAttributes();

      /* Create an XmlAttributeAttribute set it to 
      the XmlAttribute property of the XmlAttributes object.*/
      XmlAttributeAttribute myXmlAttributeAttribute = 
                                                new XmlAttributeAttribute();
      myXmlAttributeAttribute.AttributeName="Name";
      myXmlAttributes.XmlAttribute = myXmlAttributeAttribute;
      
      
      // Add to the XmlAttributeOverrides. Specify the member name.
      myXmlAttributeOverrides.Add(typeof(Student), "StudentName", 
                                                      myXmlAttributes);

      // Create the XmlSerializer.
      mySerializer = new  XmlSerializer(typeof(Student), 
                                                myXmlAttributeOverrides);
      
      writer = new StreamWriter(studentFilename);

      // Create an instance of the class that will be serialized.
      Student myStudent = new Student();

      // Set the Name property, which will be generated as an XML attribute. 
      myStudent.StudentName= "James";
      myStudent.StudentNumber=1;
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myStudent);
      writer.Close();

      // Create the XmlAttributeOverrides and XmlAttributes objects.
      XmlAttributeOverrides myXmlBookAttributeOverrides = 
                                                new XmlAttributeOverrides();
      XmlAttributes myXmlBookAttributes = new XmlAttributes();

      /* Create an XmlAttributeAttribute set it to 
      the XmlAttribute property of the XmlAttributes object.*/
      XmlAttributeAttribute myXmlBookAttributeAttribute = 
                                           new XmlAttributeAttribute("Name");
      myXmlBookAttributes.XmlAttribute = myXmlBookAttributeAttribute;
      
      
      // Add to the XmlAttributeOverrides. Specify the member name.
      myXmlBookAttributeOverrides.Add(typeof(Book), "BookName", 
                                             myXmlBookAttributes);

      // Create the XmlSerializer.
      mySerializer = new  XmlSerializer(typeof(Book), 
                                       myXmlBookAttributeOverrides);
      
      writer = new StreamWriter(bookFilename);

      // Create an instance of the class that will be serialized.
      Book myBook = new Book();

      // Set the Name property, which will be generated as an XML attribute. 
      myBook.BookName= ".NET";
      myBook.BookNumber=10;
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myBook);
      writer.Close();

   }
}

    

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the XmlAttributeAttribute class.
C# Syntax:
public XmlAttributeAttribute(
   Type type
);
Parameters:

type

The Type used to store the attribute.

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the XmlAttributeAttribute class.
C# Syntax:
public XmlAttributeAttribute(
   string attributeName,
   Type type
);
Parameters:

attributeName

The name of the XML attribute that is generated.

type

The Type used to store the attribute.

Return to top


Property: AttributeName (read-write)
Summary
Gets or sets the name of the XML attribute.
C# Syntax:
public string AttributeName {get; set;}
Remarks
Use the XmlAttributeAttribute.AttributeName property to specify an XML attribute name when the default value cannot be used. For example, if the XML attribute name is invalid as a member identifier, you can use a valid name for the identifier while setting the XmlAttributeAttribute.AttributeName to an invalid name.
Example
The following example sets the XmlAttributeAttribute.AttributeName property of an XmlAttributeAttribute.
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Group
{
   // Change the XML attribute name.
   [XmlAttribute(AttributeName = "MgrName")]
   public string Name;
   /* Use the AttributeName to collect all the XML attributes
   in the XML-document instance. */
}

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      /* To use the AttributeName to collect all the
      XML attributes. Call SerializeObject to generate 
      an XML document and alter the document by adding
      new XML attributes to it. Then comment out the SerializeObject
      method, and call DeserializeObject. */
      test.SerializeObject("MyAtts.xml");
      test.DeserializeObject("MyAtts.xml");
}
public void SerializeObject(string filename)
{
   Console.WriteLine("Serializing");
   // Create an instance of the XmlSerializer class.
   XmlSerializer mySerializer =  new XmlSerializer(typeof(Group));
   // Writing the file requires a TextWriter.
   TextWriter writer = new StreamWriter(filename);
   // Create an instance of the class that will be serialized.
   Group myGroup = new Group();
   /* Set the Name property, which will be generated
   as an XML attribute. */
   myGroup.Name = "Wallace";
   // Serialize the class, and close the TextWriter.
   mySerializer.Serialize(writer, myGroup);
   writer.Close();
}

   public void DeserializeObject(string filename)
   {
      Console.WriteLine("Deserializing");
      XmlSerializer mySerializer =
      new XmlSerializer(typeof(Group));
      FileStream fs = new FileStream(filename, FileMode.Open);
      Group myGroup = (Group)
      mySerializer.Deserialize(fs);
      Console.WriteLine(myGroup.Name);
   }
}
   

    
See also:
XmlElementAttribute.ElementName

Return to top


Property: DataType (read-write)
Summary
Gets or sets the XSD data type of the XML attribute generated by the XmlSerializer.
C# Syntax:
public string DataType {get; set;}
Remarks
The following table lists the XSD simple data types with their .NET equivalents.

For the XSD base64Binary and hexBinary data types, use an array of Byte structures, and apply a XmlArrayItemAttribute with the XmlAttributeAttribute.DataType property set to "base64Binary" or "hexBinary", as appropriate. For the XSD time and date data types, use the DateTime type and apply the XmlAttributeAttribute with the XmlAttributeAttribute.DataType set to "date" or "time".

For every XSD type that is mapped to a string, apply the XmlAttributeAttribute with its XmlAttributeAttribute.DataType property set to the XSD type. However, this will not change the serialization format, only the schema for the member.



Note The property is case-sensitive, so you must set it exactly to one of the XSD data types.

Note Passing binary data as an XML element is more efficient then passing it as an XML attribute.

For more information about XML data types, see the World Wide Web Consortium (www.w3.org ) document named "XML Schema Part 2: Datatypes".



XSD data type .NET data type
anyURI String
base64Binary Array of Byte objects
boolean Boolean
byte SByte
date DateTime
dateTime DateTime
decimal Decimal
double Double
ENTITY String
ENTITIES String
float Single
gDay String
gMonth String
gMonthDay String
gYear String
gYearMonth String
hexBinary Array of Byte objects
ID String
IDREF String
IDREFS String
int Int32
integer String
language String
long Int64
Name String
NCName String
negativeInteger String
NMTOKEN String
NMTOKENS String
normalizedString String
nonNegativeInteger String
nonPositiveInteger String
NOTATION String
positiveInteger String
QName XmlQualifiedName
recurringDate String
duration String
string String
short Int16
time DateTime
token String
unsignedByte Byte
unsignedInt UInt32
unsignedLong UInt64
unsignedShort UInt16
Example
The following example applies the XmlAttributeAttribute to two members, and sets the XmlAttributeAttribute.DataType property set to different values.
public class Group{
   [XmlAttribute(DataType = "string")]
   public string Name;
	
   [XmlAttribute (DataType = "base64Binary")]
   public byte[] Hex64Code;
}


    

Return to top


Property: Form (read-write)
Summary
Gets or sets a value indicating whether the XML attribute name generated by the XmlSerializer is qualified.
C# Syntax:
public XmlSchemaForm Form {get; set;}
Remarks
The XmlAttributeAttribute.Form property determines whether an XML element is qualified or unqualified. The XmlAttributeAttribute.Form property conforms to the 1999 http://www.w3.org specification Namespaces in XML.

If the XmlAttributeAttribute.Namespace property is set to any value, attempting to set the XmlElementAttribute.Form property to XmlSchemaForm.Unqualified throws an exception.

The default setting, XmlSchemaForm.None, instructs the XmlSerializer to check the schema for the XML document to determine whether the namespace is qualified. If the schema does not specify a value for an individual element or attribute, the XmlSerializer uses the elementFormDefault and attributeFormDefault values to determine whether an element or attribute is qualified. The XML code below shows a schema:
              <schema elementFormDefault="qualified" 
              attributeFormDefault="unqualified" ... >
                 <element name="Name"/>
                 <attribute name="Number"/>
              </schema>
            
When the XmlSerializer reads the schema, the XmlAttributeAttribute.Form value for both the Name and Number will be XmlSchemaForm.None, but the Name element will be qualified, while the Number element will be unqualified.
Example
The following example applies the XmlAttributeAttribute to two fields contained in a class.
public class Vehicle
{
   [XmlAttribute(Form = XmlSchemaForm.Qualified)]
   public string Maker;
 
   [XmlAttribute(Form = XmlSchemaForm.Unqualified)]
   public string ModelID;
}


    

Return to top


Property: Namespace (read-write)
Summary
Gets or sets the XML namespace of the XML attribute.
C# Syntax:
public string Namespace {get; set;}
Remarks
The XmlAttributeAttribute.Namespace property conforms to the http://www.w3.org specification Namespaces in XML. To create namespaces that are associated with prefixes, you must create an XmlSerializerNamespaces object that contains the namespaces and prefixes used in the XML document. The namespace you set for each XmlAttributeAttribute must match one of the namespaces in the XmlSerializerNamespaces object. When the XmlSerializer generates the XML code, it correctly prefixes each attribute name.
Example
The following example applies the XmlAttributeAttribute to two fields contained in a class. The example sets the XmlAttributeAttribute.Namespace property for each attribute to a value different from the member identifier.
public class Car
{
   [XmlAttribute(Namespace = "Make")]
   public string MakerName;

   [XmlAttribute(Namespace = "Model")]
   public string ModelName;
}


    

Return to top


Property: Type (read-write)
Summary
Gets or sets the complex type of the XML attribute.
C# Syntax:
public Type Type {get; set;}

Return to top


Property: TypeId (read-only)
Inherited
See base class member description: System.Attribute.TypeId

Summary
When implemented in a derived class, gets a unique identifier for this Attribute.
C# Syntax:
public virtual object TypeId {get;}
Remarks
As implemented, this identifier is merely the Type of the attribute. However, it is intended that the unique identifier be used to identify two attributes of the same type.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlAttributeAttribute();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Attribute.GetHashCode

Summary
Returns the hash code for this instance.
C# Syntax:
public override int GetHashCode();
Return Value:
A 32-bit signed integer hash code.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: IsDefaultAttribute()
Inherited
See base class member description: System.Attribute.IsDefaultAttribute

Summary
When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
C# Syntax:
public virtual bool IsDefaultAttribute();
Return Value:
true if this instance is the default attribute for the class; otherwise, false.
Remarks
The default implementation of this class returns false, and must be implemented in the derived class to be useful to that class.

The implementation of this method in a derived class compares the value of this instance to a standard, default value obtained by some means, then returns a Boolean value that indicates whether the value of this instance is equal to the standard. The standard value is typically coded as a constant in the implementation, or stored programmatically in a field used by the implementation.

Return to top


Method: Match(
   object obj
)
Inherited
See base class member description: System.Attribute.Match

Summary
When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
C# Syntax:
public virtual bool Match(
   object obj
);
Parameters:

obj

An Object to compare with this instance of Attribute.

Return Value:
true if this instance equals obj; otherwise, false.
Remarks
This method determines if one Attribute equals another. Its default implementation is the same as Attribute.Equals, which performs a value and reference comparison. Override this method to implement support for attribute values, such as flags or bitfields, that consist of components that are meaningful in themselves. For example, consider an attribute whose value is a binary field divided into a bitfield of flags. Two instances of this attribute have one flag in set in common while all the other flags differ. The Equal method cannot determine that the two instances have the same flag set, but the Match method can.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.