[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] |
An XML document usually contains XML elements, each of which consists of three parts: an opening tag with possible attributes, a closing tag, and the data between the tags. XML tags can be nested--that is, the data between tags can also be XML elements. This capacity of one element to enclose another allows the document to contain hierarchies of data. An XML element can also include attributes.
Apply the XmlElementAttribute to public fields or public read/write properties to control characteristics of the XML elements such as the element name and namespace.
The XmlElementAttribute can be applied multiple times to a field that returns an array of objects. The purpose of this is to specify (through the XmlElementAttribute.Type property) different types that can be inserted into the array. For example, the array in the C# code below accepts both strings and integers.
public class Things{ [XmlElement(DataType = typeof(string)), XmlElement(DataType = typeof(int))] public object[] StringsAndInts; }
This results in XML that might resemble the following.
<Things> <string>Hello</string> <int>999</int> <string>World</string> </Things>
Note that when you apply the XmlElementAttribute multiple times without specifying an XmlElementAttribute.ElementName property value, the elements are named after the type of the acceptable objects.
If you apply the XmlElementAttribute to a field or property that returns an array, the items in the array are encoded as a sequence of XML elements.
In contrast, if an XmlElementAttribute is not applied to such a field or property, the items in the array are encoded as a sequence of elements, nested under an element named after the field or property. (Use the XmlArrayAttribute and XmlArrayItemAttribute attributes to control how an array is serialized.)
You can set the XmlElementAttribute.Type property to specify a type that is derived from the type of the original field or property--that is, the field or property to which you have applied the XmlElementAttribute.
If a field or property returns an ArrayList, you can apply multiple instances of the XmlElementAttribute to the member. For each instance, set the XmlElementAttribute.Type property to a type of object that can be inserted into the array.
For more information about using attributes, see the conceptual topic at MSDN: extendingmetadatausingattributes.
Group
and applies the XmlElementAttribute to several of its members. The field named
Employees
returns an array of
Employee
objects. In this case, the XmlElementAttribute specifies that that the resulting XML should not be nested (which is the default behavior of items in an array).using System; using System.Collections; using System.IO; using System.Xml.Serialization; public class Group { /* Set the element name and namespace of the XML element. By applying an XmlElementAttribute to an array, you instruct the XmlSerializer to serialize the array as a series of XML elements, instead of a nested set of elements. */ [XmlElement( ElementName = "Members", Namespace = "http://www.cpandl.com")] public Employee[] Employees; [XmlElement(DataType = "double", ElementName = "Building")] public double GroupID; [XmlElement(DataType = "hexBinary")] public byte [] HexBytes; [XmlElement(DataType = "boolean")] public bool IsActive; [XmlElement(Type = typeof(Manager))] public Employee Manager; [XmlElement(typeof(int), ElementName = "ObjectNumber"), XmlElement(typeof(string), ElementName = "ObjectString")] public ArrayList ExtraInfo; } public class Employee { public string Name; } public class Manager:Employee{ public int Level; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("FirstDoc.xml"); test.DeserializeObject("FirstDoc.xml"); } public void SerializeObject(string filename) { // Create the XmlSerializer. XmlSerializer s = new XmlSerializer(typeof(Group)); // To write the file, a TextWriter is required. TextWriter writer = new StreamWriter(filename); /* Create an instance of the group to serialize, and set its properties. */ Group group = new Group(); group.GroupID = 10.089f; group.IsActive = false; group.HexBytes = new byte[1]{Convert.ToByte(100)}; Employee x = new Employee(); Employee y = new Employee(); x.Name = "Jack"; y.Name = "Jill"; group.Employees = new Employee[2]{x,y}; Manager mgr = new Manager(); mgr.Name = "Sara"; mgr.Level = 4; group.Manager = mgr; /* Add a number and a string to the ArrayList returned by the ExtraInfo property. */ group.ExtraInfo = new ArrayList(); group.ExtraInfo.Add(42); group.ExtraInfo.Add("Answer"); // Serialize the object, and close the TextWriter. s.Serialize(writer, group); writer.Close(); } public void DeserializeObject(string filename) { FileStream fs = new FileStream(filename, FileMode.Open); XmlSerializer x = new XmlSerializer(typeof(Group)); Group g = (Group) x.Deserialize(fs); Console.WriteLine(g.Manager.Name); Console.WriteLine(g.GroupID); Console.WriteLine(g.HexBytes[0]); foreach(Employee e in g.Employees) { Console.WriteLine(e.Name); } } }
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 XmlElementAttribute class. |
ctor #2 | Overloaded:.ctor(string elementName) Initializes a new instance of the XmlElementAttribute class and specifies the name of the XML element. |
ctor #3 | Overloaded:.ctor(Type type) Initializes a new instance of the XmlElementAttribute class and specifies a type for the member to which the XmlElementAttribute is applied, which is used by the XmlSerializer when serializing or deserializing a containing object. |
ctor #4 | Overloaded:.ctor(string elementName, Type type) Initializes a new instance of the XmlElementAttribute; specifies the name of the XML element and a derived type for the member to which the XmlElementAttribute is applied, which is used when the XmlSerializer serializes a containing object. |
DataType | Read-write Gets or sets the XML Schema definition (XSD) data type of the XMl element generated by the XmlSerializer. |
ElementName | Read-write Gets or sets the name of the generated XML element. |
Form | Read-write Gets or sets a value indicating whether the element is qualified. |
IsNullable | Read-write Gets or sets a value indicating whether the XmlSerializer should serialize a member that is set to null as an empty tag with the xsi:nil attribute set to true. |
Namespace | Read-write Gets or sets the namespace assigned to the XML element that results when the class is serialized. |
Type | Read-write Gets or sets the object type used to represent the XML 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. |
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. |
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:
public XmlElementAttribute(); |
public class MyClass { [XmlElement()] public string TeacherName; }
public XmlElementAttribute( |
elementName
Cars
, pass it in the elementName parameter.
Vehicles
. The example applies the XmlElementAttribute to the field and includes the elementName parameter, thereby instructing the XmlSerializer to generate XML elements named "Cars" rather than "Vehicles".public class Transportation { [XmlElement("Cars")] public string Vehicles; }
public XmlElementAttribute( |
type
MyAnimal
returns an
Animal
object. You want to enhance the object, so you create a new class named
Mammal
that inherits from the
Animal
class. To instruct the XmlSerializer to accept the Mammal class when it serializes the
MyAnimal
property, pass the Type of the
Mammal
class to the constructor.
Orchestra
that contains a single field named
Instruments
, which returns an array of
Instrument
objects. A second class named
Brass
inherits from the
Instrument
class. The example applies the XmlElementAttribute to the
Instruments
field, and specifies the
Brass
type, allowing the
Instruments
field to accept
Brass
objects. The example also specifies the name of the XML element by setting the XmlElementAttribute.ElementName property.using System; using System.IO; using System.Xml.Serialization; public class Orchestra { public Instrument[] Instruments; } public class Instrument { public string Name; } public class Brass:Instrument{ public bool IsValved; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("Override.xml"); test.DeserializeObject("Override.xml"); } public void SerializeObject(string filename) { // To write the file, a TextWriter is required. TextWriter writer = new StreamWriter(filename); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // Creates an XmlElementAttribute that overrides the Instrument type. XmlElementAttribute attr = new XmlElementAttribute(typeof(Brass)); attr.ElementName = "Brass"; // Adds the element to the collection of elements. attrs.XmlElements.Add(attr); attrOverrides.Add(typeof(Orchestra), "Instruments", attrs); // Creates the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Orchestra), attrOverrides); // Creates the object to serialize. Orchestra band = new Orchestra(); // Creates an object of the derived type. Brass i = new Brass(); i.Name = "Trumpet"; i.IsValved = true; Instrument[] myInstruments = {i}; band.Instruments = myInstruments; s.Serialize(writer,band); writer.Close(); } public void DeserializeObject(string filename) { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // Creates an XmlElementAttribute that override the Instrument type. XmlElementAttribute attr = new XmlElementAttribute(typeof(Brass)); attr.ElementName = "Brass"; // Adds the element to the collection of elements. attrs.XmlElements.Add(attr); attrOverrides.Add(typeof(Orchestra), "Instruments", attrs); // Creates the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Orchestra), attrOverrides); FileStream fs = new FileStream(filename, FileMode.Open); Orchestra band = (Orchestra) s.Deserialize(fs); Console.WriteLine("Brass:"); /* Deserializing differs from serializing. To read the derived-object values, declare an object of the derived type (Brass) and cast the Instrument instance to it. */ Brass b; foreach(Instrument i in band.Instruments) { b= (Brass)i; Console.WriteLine( b.Name + "\n" + b.IsValved); } } }
elementName
type
Use the type parameter to specify a type that is derived from a base class. For example, suppose a property named MyAnimal returns an Animal object. You want to enhance the object, so you create a new class named Mammal that inherits from the Animal class. To instruct the XmlSerializer to accept the Mammal class when it serializes the MyAnimal property, pass the Type of the Mammal class to the constructor.
Orchestra
that contains a single field named
Instruments
, which returns an array of
Instrument
objects. A second class named
Brass
inherits from the
Instrument
class. The example applies the XmlElementAttribute to the
Instruments
field, and specifies the
Brass
type, allowing the
Instruments
field to accept
Brass
objects. The example also specifies the name of the XML element by setting the XmlElementAttribute.ElementName property.using System; using System.IO; using System.Xml.Serialization; public class Orchestra { public Instrument[] Instruments; } public class Instrument { public string Name; } public class Brass:Instrument{ public bool IsValved; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("Override.xml"); test.DeserializeObject("Override.xml"); } public void SerializeObject(string filename) { // To write the file, a TextWriter is required. TextWriter writer = new StreamWriter(filename); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // Creates an XmlElementAttribute that overrides the Instrument type. XmlElementAttribute attr = new XmlElementAttribute(typeof(Brass)); attr.ElementName = "Brass"; // Adds the element to the collection of elements. attrs.XmlElements.Add(attr); attrOverrides.Add(typeof(Orchestra), "Instruments", attrs); // Creates the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Orchestra), attrOverrides); // Creates the object to serialize. Orchestra band = new Orchestra(); // Creates an object of the derived type. Brass i = new Brass(); i.Name = "Trumpet"; i.IsValved = true; Instrument[] myInstruments = {i}; band.Instruments = myInstruments; s.Serialize(writer,band); writer.Close(); } public void DeserializeObject(string filename) { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // Creates an XmlElementAttribute that override the Instrument type. XmlElementAttribute attr = new XmlElementAttribute(typeof(Brass)); attr.ElementName = "Brass"; // Adds the element to the collection of elements. attrs.XmlElements.Add(attr); attrOverrides.Add(typeof(Orchestra), "Instruments", attrs); // Creates the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Orchestra), attrOverrides); FileStream fs = new FileStream(filename, FileMode.Open); Orchestra band = (Orchestra) s.Deserialize(fs); Console.WriteLine("Brass:"); /* Deserializing differs from serializing. To read the derived-object values, declare an object of the derived type (Brass) and cast the Instrument instance to it. */ Brass b; foreach(Instrument i in band.Instruments) { b= (Brass)i; Console.WriteLine( b.Name + "\n" + b.IsValved); } } }
public string DataType {get; set;}
|
Exception Type | Condition |
---|---|
Exception | The XML Schema data type you've specified cannot be mapped to the .NET data type. |
For the XML Schema base64Binary and hexBinary data types, use an array of Byte structures, and apply a XmlElementAttribute with the XmlElementAttribute.DataType set to "base64Binary" or "hexBinary", as appropriate. For the XML Schema time and date data types, use the DateTime type and apply the XmlElementAttribute with the XmlElementAttribute.DataType set to "date" or "time".
For every XML Schema type that is mapped to a string, apply the XmlElementAttribute with its XmlElementAttribute.DataType property set to the XML Schema type. Not that this will not change the serialization format, only the schema for the member.
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 |
using System; using System.Collections; using System.IO; using System.Xml.Serialization; public class Group { /* Apply two XmlElementAttributes to the field. Set the DataType to string an int to allow the ArrayList to accept both types. The Namespace is also set to different values for each type. */ [XmlElement(DataType = "string", Type = typeof(string), Namespace = "http://www.cpandl.com"), XmlElement(DataType = "int", Namespace = "http://www.cohowinery.com", Type = typeof(int))] public ArrayList ExtraInfo; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("ElementTypes.xml"); } public void SerializeObject(string filename) { // A TextWriter is needed to write the file. TextWriter writer = new StreamWriter(filename); // Create the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Group)); // Create the object to serialize. Group myGroup = new Group(); /* Add a string and an integer to the ArrayList returned by the ExtraInfo field. */ myGroup.ExtraInfo = new ArrayList(); myGroup.ExtraInfo.Add("hello"); myGroup.ExtraInfo.Add(100); // Serialize the object and close the TextWriter. s.Serialize(writer,myGroup); writer.Close(); } }
public string ElementName {get; set;}
|
You can set the same XmlArrayAttribute.ElementName value to more than one class member if the generated XML document uses XML namespaces to distinguish between the identically named members. For details on how to use namespaces and prefixed names in the XML document, see the XmlSerializerNamespaces class.
// This is the class that will be serialized. public class XClass { /* The XML element name will be XName instead of the default ClassName. */ [XmlElement(ElementName = "XName")] public string ClassName; }
public XmlSchemaForm Form {get; set;}
|
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.public class MyClass { [XmlElement(Form = XmlSchemaForm.Unqualified)] public string ClassName; }
public bool IsNullable {get; set;}
|
If the XmlElementAttribute.IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to null. For example, if you set a field named MyStringArray to null, the XmlSerializer generates the following XML code.
<MyStringArray xsi:nil = "true" />
If the XmlElementAttribute.IsNullable property is false, no XML element is generated.
public class MyClass { [XmlElement(IsNullable = false)] public string Group; }
public string Namespace {get; set;}
|
To create namespaces that are associated with a prefix, you must create an XmlSerializerNamespaces that contains the namespaces and prefixes used in the XML document. As you set the namespace for each XmlArrayAttribute, it must match one of the namespaces in the XmlSerializerNamespaces. When the XML is generated, each array will be correctly prefixed with the prefix associated with the specified namespace.
public Type Type {get; set;}
|
If a field or property returns an ArrayList, you can apply multiple instances of the XmlElementAttribute to the member. For each instance, set the XmlElementAttribute.Type property to a type of object that can be inserted into the array.
using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Serialization; public class Group { [XmlElement(typeof(Manager))] public Employee [] Staff; [XmlElement (typeof(int)), XmlElement (typeof(string)), XmlElement (typeof(DateTime))] public ArrayList ExtraInfo; } public class Employee { public string Name; } public class Manager:Employee { public int Level; } public class Run { public static void Main() { Run test = new Run(); test.SerializeObject("TypeEx.xml"); } public void SerializeObject(string filename) { // Create an XmlSerializer instance. XmlSerializer xSer = new XmlSerializer(typeof(Group)); // Create object and serialize it. Group myGroup = new Group(); Manager e1 = new Manager(); e1.Name = "Manager1"; Manager m1 = new Manager(); m1.Name = "Manager2"; m1.Level = 4; Employee[] emps = {e1, m1}; myGroup.Staff = emps; myGroup.ExtraInfo = new ArrayList(); myGroup.ExtraInfo.Add(".NET"); myGroup.ExtraInfo.Add(42); myGroup.ExtraInfo.Add(new DateTime(2001,1,1)); TextWriter writer = new StreamWriter(filename); xSer.Serialize(writer, myGroup); writer.Close(); } }
public virtual object TypeId {get;}
|
~XmlElementAttribute(); |
public override int GetHashCode(); |
public Type GetType(); |
public virtual bool IsDefaultAttribute(); |
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.
obj
protected object MemberwiseClone(); |
public virtual string ToString(); |