System.Xml.Serialization.XmlRootAttribute Class

Assembly: System.Xml.dll
Namespace: System.Xml.Serialization
Summary
Identifies a class, structure, enumeration, or interface as the root (or top-level) element of an XML-document instance.
C# Syntax:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.ReturnValue)]
public class XmlRootAttribute : Attribute
Remarks
The XmlRootAttribute 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.

You can apply the XmlRootAttribute to a class, struct, enumeration, or interface. You can also apply the attribute to the return value of an XML Web service method.

Every XML document must have a single root element that contains all the other elements. The XmlRootAttribute allows you to control how the XmlSerializer generates the root element by setting certain properties. For example, specify the name of the generated XML element by setting the XmlRootAttribute.ElementName property.

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



Note In your code, you can use the word XmlRoot instead of the longer XmlRootAttribute.
Example
The following example applies the XmlRootAttribute to a class. The attribute specifies the element name, namespace, and whether the element is qualified, and whether the xsi:nil attribute will be generated if the class is set to null.
[XmlRootAttribute(Namespace="http://www.cpandl.com",
ElementName = "MyClassName", Form = XmlSchemaForm.Qualified,
IsNullable = false)]
public class MyClass
{
   private string mystring;
   public string MyStringProperty
   {
      get{return mystring;}
      set{mystring = value;}
   }
}


    
See also:
System.Xml.Serialization Namespace | XmlArrayAttribute | XmlElementAttribute | XmlSerializer | MSDN: introducingxmlserialization | MSDN: overridingserializationofclasseswithxmlattributeoverridesclass | XmlAttributes | MSDN: controllingserializationbyxmlserializerwithattributes | MSDN: anexampleofxmlserializationwithxmlserializer

System.Xml.Serialization.XmlRootAttribute 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 XmlRootAttribute class.
ctor #2 Overloaded:
.ctor(string elementName)

Initializes a new instance of the XmlRootAttribute class, and specifies the name of the XML root element.
Public Properties
DataType Read-write

Gets or sets the XSD data type of the XML root element.
ElementName Read-write

Gets or sets the name of the XML element that is generated and recognized by the XmlSerializer class's XmlSerializer.Serialize and XmlSerializer.Deserialize methods, respectively.
IsNullable Read-write

Gets or sets a value indicating whether the XmlSerializer should serialize a member that is set to null into the xsi:nil attribute set to true.
Namespace Read-write

Gets or sets the namespace for the XML root element.
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.XmlRootAttribute Member Details

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

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlRootAttribute();
Example
The following example creates an instance of an XmlRootAttribute and assigns it to the XmlAttributes.XmlRoot property of an XmlAttributes object. When the XmlSerializer serializes the MyClass object, it uses the XmlRootAttribute object to override the default root element.
using System;
using System.IO;
using System.Xml.Serialization;

// This is the class that is the default root element.
public class MyClass
{
   public string Name;
}

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

   public void SerializeOrder(string filename)
   {
      // Create an XmlSerializer instance using the method below.
      XmlSerializer xSer = CreateOverrider();

      // Create the object, and set its Name property.
      MyClass myClass = new MyClass();
      myClass.Name = "New Class Name";

      // Serialize the class, and close the TextWriter.
      TextWriter writer = new StreamWriter(filename);
      xSer.Serialize(writer, myClass);
      writer.Close();
   }

   // Return an XmlSerializer to override the root serialization.
   public XmlSerializer CreateOverrider()
   {
      // Create an XmlAttributes to override the default root element.
      XmlAttributes attrs = new XmlAttributes();

      // Create an XmlRootAttribute and set its element name and namespace.
      XmlRootAttribute xRoot = new XmlRootAttribute();
      xRoot.ElementName = "OverriddenRootElementName";
      xRoot.Namespace = "http://www.microsoft.com";

      // Set the XmlRoot property to the XmlRoot object.
      attrs.XmlRoot = xRoot;
      XmlAttributeOverrides xOver = new XmlAttributeOverrides();
      
      /* Add the XmlAttributes object to the 
      XmlAttributeOverrides object. */
      xOver.Add(typeof(MyClass), attrs);

      // Create the Serializer, and return it.
      XmlSerializer xSer = new XmlSerializer
      (typeof(MyClass), xOver);
      return xSer;
   }
}


    
See also:
XmlAttributes.XmlRoot | XmlAttributeOverrides

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the XmlRootAttribute class, and specifies the name of the XML root element.
C# Syntax:
public XmlRootAttribute(
   string elementName
);
Parameters:

elementName

The name of the XML root element.

Example
The following example creates an instance of the XmlRootAttribute and uses it to override the serialization of an instance of A class named "Student".
   public void SerializeOrder(string filename)
   {
      // Create an XmlSerializer instance using the method below.
      XmlSerializer myXmlSerializer = CreateOverrider();

      // Create the object, and set its Name property.
      Student myStudent = new Student();
      myStudent.Name = "Student class1";

      // Serialize the class, and close the TextWriter.
      TextWriter writer = new StreamWriter(filename);
      myXmlSerializer.Serialize(writer, myStudent);
      writer.Close();
   }

   // Return an XmlSerializer to override the root serialization.
   public XmlSerializer CreateOverrider()
   {
      // Create an XmlAttributes to override the default root element.
      XmlAttributes myXmlAttributes = new XmlAttributes();

      // Create an XmlRootAttribute overloaded constructer 
      //and set its namespace.
      XmlRootAttribute myXmlRootAttribute = 
                     new XmlRootAttribute("OverriddenRootElementName");
      myXmlRootAttribute.Namespace = "http://www.microsoft.com";

      // Set the XmlRoot property to the XmlRoot object.
      myXmlAttributes.XmlRoot = myXmlRootAttribute;
      XmlAttributeOverrides myXmlAttributeOverrides = 
                                          new XmlAttributeOverrides();
      
      /* Add the XmlAttributes object to the 
      XmlAttributeOverrides object. */
      myXmlAttributeOverrides.Add(typeof(Student), myXmlAttributes);

      // Create the Serializer, and return it.
      XmlSerializer myXmlSerializer = new XmlSerializer
         (typeof(Student), myXmlAttributeOverrides);
      return myXmlSerializer;
   }

    
See also:
XmlRootAttribute.ElementName

Return to top


Property: DataType (read-write)
Summary
Gets or sets the XSD data type of the XML root element.
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 XmlRootAttribute with the XmlRootAttribute.DataType property set to "base64Binary" or "hexBinary", as appropriate. For the XSD time and date data types, use the DateTime type and apply the XmlRootAttribute with the XmlRootAttribute.DataType set to "date" or "time".

For every XSD type that is mapped to a string, apply the XmlRootAttribute with its XmlRootAttribute.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

Return to top


Property: ElementName (read-write)
Summary
Gets or sets the name of the XML element that is generated and recognized by the XmlSerializer class's XmlSerializer.Serialize and XmlSerializer.Deserialize methods, respectively.
C# Syntax:
public string ElementName {get; set;}
Remarks
Specify an XmlArrayItemAttribute.ElementName if you want the name of the generated XML element to differ from the class name.
Example
The following example creates an instance of the XmlRootAttribute class and sets the XmlRootAttribute.ElementName property to a new value. The object is then used to create an XmlAttributeOverrides object used to override the serialization of an object.
   public void SerializeOrder(string filename)
   {
      // Create an XmlSerializer instance using the method below.
      XmlSerializer myXmlSerializer = CreateOverrider();

      // Create the object, and set its Name property.
      Student myStudent = new Student();
      myStudent.Name = "Student class1";

      // Serialize the class, and close the TextWriter.
      TextWriter writer = new StreamWriter(filename);
      myXmlSerializer.Serialize(writer, myStudent);
      writer.Close();
   }

   // Return an XmlSerializer to override the root serialization.
   public XmlSerializer CreateOverrider()
   {
      // Create an XmlAttributes to override the default root element.
      XmlAttributes myXmlAttributes = new XmlAttributes();

      // Create an XmlRootAttribute and set its element name and namespace.
      XmlRootAttribute myXmlRootAttribute = new XmlRootAttribute();
      myXmlRootAttribute.ElementName = "OverriddenRootElementName";
      myXmlRootAttribute.Namespace = "http://www.microsoft.com";

      // Set the XmlRoot property to the XmlRoot object.
      myXmlAttributes.XmlRoot = myXmlRootAttribute;
      XmlAttributeOverrides myXmlAttributeOverrides = 
                                    new XmlAttributeOverrides();
      
      /* Add the XmlAttributes object to the 
      XmlAttributeOverrides object. */
      myXmlAttributeOverrides.Add(typeof(Student), myXmlAttributes);

      // Create the Serializer, and return it.
      XmlSerializer myXmlSerializer = new XmlSerializer
         (typeof(Student), myXmlAttributeOverrides);
      return myXmlSerializer;
   }

    

Return to top


Property: IsNullable (read-write)
Summary
Gets or sets a value indicating whether the XmlSerializer should serialize a member that is set to null into the xsi:nil attribute set to true.
C# Syntax:
public bool IsNullable {get; set;}
Remarks
The XML schema specification for structures allows an XML document to explicitly signal that an element's content is missing. Such an element contains the attribute xsi:nil set to true. For more information, see the http://www.w3.org/TR/xmlschema-1/ specification named XML Schema Part 1: Structures.

If the XmlRootAttribute.IsNullable property is set to true, the xsi:nil attribute is generated as shown in the following XML:

              <?xml version="1.0" encoding="utf-8"?>
              <Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
              xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:nil="true" />
            

If the XmlRootAttribute.IsNullable property is false, an empty element is created as shown below:

              <?xml version="1.0" encoding="utf-8"?>
              <Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
              xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
            
Example
The following example serializes a class named Group. The example applies the XmlRootAttribute to the class, and sets the XmlRootAttribute.IsNullable property to false.
using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

// Apply the XmlRootAttribute and set the IsNullable property to false.
[XmlRoot(IsNullable = false)]
public class Group
{   
   public string Name;
}   


public class Run
{
   public static void Main()
   {
   Console.WriteLine("Running");
      Run test = new Run();
      test.SerializeObject("NullDoc.xml");

   }

   public void SerializeObject(string filename)
   {
      XmlSerializer s = new XmlSerializer(typeof(Group));

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

      // Create the object to serialize.
      Group mygroup = null;
      
      // Serialize the object, and close the TextWriter.
      s.Serialize(writer, mygroup);
      writer.Close();
   }
}
   

    

Return to top


Property: Namespace (read-write)
Summary
Gets or sets the namespace for the XML root element.
C# Syntax:
public string Namespace {get; set;}
Remarks
The XmlArrayItemAttribute.Namespace property conforms to the World Wide Web Consortium (www.w3.org ) specification named Namespaces in XML.

To create prefixed namespaces in the XML document, create an XmlSerializerNamespaces object that contains all the prefix-namespace pairs. The namespace you set for each XmlArrayAttribute must be contained in the XmlSerializerNamespaces object. When the XmlSerializer generates the document, it correctly prefixes the element name for each array item.

Example
The following example applies the XmlRootAttribute to a class and sets the XmlRootAttribute.Namespace property.
[XmlRoot(Namespace = "http://www.cpandl.com")]
public class Group
{
   // Insert the members of the Group class.
}
   

    
See also:
XmlAttributeOverrides | XmlAttributes | XmlAttributes.XmlRoot

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:
~XmlRootAttribute();

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.