System.Xml.Serialization.XmlTextAttribute Class

Assembly: System.Xml.dll
Namespace: System.Xml.Serialization
Summary
Indicates to the XmlSerializer that the member should be treated as XML text when the containing class is serialized or deserialized.
C# Syntax:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class XmlTextAttribute : Attribute
Remarks
The XmlTextAttribute belongs to a family of attributes that controls how the XmlSerializer serializes and deserializes an object (through its XmlSerializer.Serialize and XmlSerializer.Deserialize methods). See the conceptual topic at MSDN: attributesthatcontrolserialization for a complete list of similar attributes.

Only one instance of the XmlTextAttribute class can be applied in a class.

You can apply the XmlTextAttribute to public fields and public read/write properties that return primitive and enumeration types.

You can apply the XmlTextAttribute to a field or property that returns an array of strings. You can also apply the attribute to an array of type Object but you must set the XmlTextAttribute.Type property to string. In that case, any strings inserted into the array will be serialized as XML text.

The XmlTextAttribute can also be applied to a field that returns an XmlNode or an array of XmlNode objects.

By default, the XmlSerializer serializes a class member as an XML element. However, if you apply the XmlTextAttribute to a member, the XmlSerializer translates its value into XML text. This means that the value will be encoded into the content of an XML element.

The the conceptual topic at MSDN: xmlschemadefinitiontoolxsdexe occasionally generates the XmlTextAttribute when creating classes from an XML Schema definition (XSD) file. This occurs when the schema contains a complexType with mixed content; in that case, the corresponding class will contain a member that returns a string array to which the XmlTextAttribute is applied. For example, when the Xml Schema Definition tool processes this schema:

          <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="" 
          xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:element name="LinkList" type="LinkList" />
            <xs:complexType name="LinkList" mixed="true">
              <xs:sequence>
                <xs:element minOccurs="1" maxOccurs="1" name="id" type="xs:int" />
                <xs:element minOccurs="0" maxOccurs="1" name="name" type="xs:string" />
                <xs:element minOccurs="0" maxOccurs="1" name="next" type="LinkList" />
              </xs:sequence>
            </xs:complexType>
          </xs:schema>
        

the following class will be generated:

          ' Visual Basic code
          Public Class LinkList 
             Public id As Integer
             Public string name
             Public LinkList next
             <System.Xml.Serialization.XmlTextAttribute()> _
             Public Text() As string
          End Class
          // C# code
          public class LinkList {
             public int id;
             public string name;
             public LinkList next;
             [System.Xml.Serialization.XmlTextAttribute()]
             public string[] Text;
          }
        

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



Note In your code, you can use the word XmlText instead of the longer XmlTextAttribute.
Example
using System;
using System.Xml.Serialization;
using System.IO;


public class Group1{
   // The XmlTextAttribute with type set to string informs the 
   // XmlSerializer that strings should be serialized as XML text.
   [XmlText(typeof(string))]
   [XmlElement(typeof(int))]  
   [XmlElement(typeof(double))]
   public object [] All= new object []{321, "One", 2, 3.0, "Two" };
}

public class Group2{
   [XmlText(Type = typeof(GroupType))]
   public GroupType Type;
}
public enum GroupType{
   Small,
   Medium,
   Large
}

public class Group3{
   [XmlText(Type=typeof(DateTime))]
   public DateTime CreationTime = DateTime.Now;
}

public class Test{
   static void Main(){
      Test t = new Test();
      t.SerializeArray("XmlText1.xml");
      t.SerializeEnum("XmlText2.xml");
      t.SerializeDateTime("XmlText3.xml");
   }

   private void SerializeArray(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group1));
      Group1 myGroup1 = new Group1();

      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup1);
      writer.Close();
   }

   private void SerializeEnum(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group2));
      Group2 myGroup = new Group2();
      myGroup.Type = GroupType.Medium;
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }

   private void SerializeDateTime(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group3));
      Group3 myGroup = new Group3();
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }   
}

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

System.Xml.Serialization.XmlTextAttribute 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 XmlTextAttribute class.
ctor #2 Overloaded:
.ctor(Type type)

Initializes a new instance of the XmlTextAttribute class.
Public Properties
DataType Read-write

Gets or sets the XML Schema definition language (XSD) data type of the text generated by the XmlSerializer.
Type Read-write

Gets or sets the type of the member.
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.XmlTextAttribute Member Details

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

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public XmlTextAttribute();
Remarks
You can override the way that the XmlSerializer serializes a public field or public read/write property by creating an XmlAttributes, and setting its XmlAttributes.XmlText property to an XmlTextAttribute. For more details, see the XmlAttributeOverrides class.
Example
The following example serializes a class that contains a public field, named Comment . The example applies an XmlTextAttribute to the field, thereby overriding its serialization as an XML element, and instead serializing it as XML text.
using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;


public class Group {
    public string GroupName;
    public string Comment;
}

public class Test {
    public static void Main() {
        Test t = new Test();
        t.SerializerOrder("TextOverride.xml");
    }
    /* Create an instance of the XmlSerializer class that overrides 
       the default way it serializes an object. */
    public XmlSerializer CreateOverrider() {
        /* Create instances of the XmlAttributes and 
        XmlAttributeOverrides classes. */
   
        XmlAttributes attrs = new XmlAttributes();

        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
              
        /* Create an XmlTextAttribute to override the default 
        serialization process. */
        XmlTextAttribute xText = new XmlTextAttribute();
        attrs.XmlText = xText;

        // Add the XmlAttributes to the XmlAttributeOverrides.
        xOver.Add(typeof(Group), "Comment", attrs);

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

    public void SerializerOrder(string filename) {
        // Create an XmlSerializer instance.
        XmlSerializer xSer = CreateOverrider();

        // Create the object and serialize it.
        Group myGroup = new Group();
        myGroup.Comment = "This is a great product.";
      
        TextWriter writer = new StreamWriter(filename);
        xSer.Serialize(writer, myGroup);
    }
}
   

    

Return to top


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

type

The Type of the member to be serialized.

Remarks
You can override the way that the XmlSerializer serializes a public field or public read/write property by creating an XmlAttributes, and setting its XmlAttributes.XmlText property to an XmlTextAttribute. For more details, see the XmlAttributeOverrides class.
Example
using System;
using System.Xml.Serialization;
using System.IO;


public class Group1{
   // The XmlTextAttribute with type set to string informs the 
   // XmlSerializer that strings should be serialized as XML text.
   [XmlText(typeof(string))]
   [XmlElement(typeof(int))]  
   [XmlElement(typeof(double))]
   public object [] All= new object []{321, "One", 2, 3.0, "Two" };
}

public class Group2{
   [XmlText(Type = typeof(GroupType))]
   public GroupType Type;
}
public enum GroupType{
   Small,
   Medium,
   Large
}

public class Group3{
   [XmlText(Type=typeof(DateTime))]
   public DateTime CreationTime = DateTime.Now;
}

public class Test{
   static void Main(){
      Test t = new Test();
      t.SerializeArray("XmlText1.xml");
      t.SerializeEnum("XmlText2.xml");
      t.SerializeDateTime("XmlText3.xml");
   }

   private void SerializeArray(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group1));
      Group1 myGroup1 = new Group1();

      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup1);
      writer.Close();
   }

   private void SerializeEnum(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group2));
      Group2 myGroup = new Group2();
      myGroup.Type = GroupType.Medium;
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }

   private void SerializeDateTime(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group3));
      Group3 myGroup = new Group3();
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }   
}

    

Return to top


Property: DataType (read-write)
Summary
Gets or sets the XML Schema definition language (XSD) data type of the text generated by the XmlSerializer.
C# Syntax:
public string DataType {get; set;}
Exceptions
Exception Type Condition
Exception The XML Schema data type you've specified cannot be mapped to the .NET data type.
InvalidOperationException The XML Schema data type you've specified is invalid for the property and cannot be converted to the member type.
Remarks
Setting the XmlTextAttribute.DataType property to an XML Schema simple data type affects the format of the generated XML. For example, setting the property to "date" causes the generated text to be formatted in the general date style, for example: 2001-08-31. By contrast, setting the property to "dateTime" results in a specific instant as defined by the International Organization for Standardization document 8601, "Representations of Dates and Times", for example: 2001-08-15T06:59:11.0508456-07:00.

The effect of setting the XmlTextAttribute.DataType property can also be seen when using the the conceptual topic at MSDN: xmlschemadefinitiontoolxsdexe to generate the XML Schema for a compiled file. For more information on using the tool, see the conceptual topic at MSDN: usingxmlschemadefinitiontool.

The following table lists the XML Schema simple data types with their .NET equivalents.

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

For every XML Schema data type that is mapped to a string, apply the XmlTextAttribute with its XmlTextAttribute.DataType property set to the XML Schema data type. Note that 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 XML Schema 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 Schema data types, see the World Wide Web Consortium (www.w3.org ) document named "XML Schema Part 2: Datatypes".



XML Schema 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
using System;
using System.Xml.Serialization;
using System.IO;


public class Group1{
   // The XmlTextAttribute with type set to string informs the 
   // XmlSerializer that strings should be serialized as XML text.
   [XmlText(typeof(string))]
   [XmlElement(typeof(int))]  
   [XmlElement(typeof(double))]
   public object [] All= new object []{321, "One", 2, 3.0, "Two" };
}

public class Group2{
   [XmlText(Type = typeof(GroupType))]
   public GroupType Type;
}
public enum GroupType{
   Small,
   Medium,
   Large
}

public class Group3{
   [XmlText(Type=typeof(DateTime))]
   public DateTime CreationTime = DateTime.Now;
}

public class Test{
   static void Main(){
      Test t = new Test();
      t.SerializeArray("XmlText1.xml");
      t.SerializeEnum("XmlText2.xml");
      t.SerializeDateTime("XmlText3.xml");
   }

   private void SerializeArray(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group1));
      Group1 myGroup1 = new Group1();

      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup1);
      writer.Close();
   }

   private void SerializeEnum(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group2));
      Group2 myGroup = new Group2();
      myGroup.Type = GroupType.Medium;
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }

   private void SerializeDateTime(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group3));
      Group3 myGroup = new Group3();
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }   
}

    

Return to top


Property: Type (read-write)
Summary
Gets or sets the type of the member.
C# Syntax:
public Type Type {get; set;}
Remarks
The Type property can only be set to primitive types and enumerations.

The XmlTextAttribute can also be applied to a field that returns an XmlNode or an array of XmlNode objects.

You can apply the XmlTextAttribute to a field or property that returns an array of strings. You can also apply the attribute to an array of type Object but you must set the XmlTextAttribute.Type property to string. In that case, any strings inserted into the array will be serialized as XML text.

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


public class Group1{
   // The XmlTextAttribute with type set to string informs the 
   // XmlSerializer that strings should be serialized as XML text.
   [XmlText(typeof(string))]
   [XmlElement(typeof(int))]  
   [XmlElement(typeof(double))]
   public object [] All= new object []{321, "One", 2, 3.0, "Two" };
}

public class Group2{
   [XmlText(Type = typeof(GroupType))]
   public GroupType Type;
}
public enum GroupType{
   Small,
   Medium,
   Large
}

public class Group3{
   [XmlText(Type=typeof(DateTime))]
   public DateTime CreationTime = DateTime.Now;
}

public class Test{
   static void Main(){
      Test t = new Test();
      t.SerializeArray("XmlText1.xml");
      t.SerializeEnum("XmlText2.xml");
      t.SerializeDateTime("XmlText3.xml");
   }

   private void SerializeArray(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group1));
      Group1 myGroup1 = new Group1();

      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup1);
      writer.Close();
   }

   private void SerializeEnum(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group2));
      Group2 myGroup = new Group2();
      myGroup.Type = GroupType.Medium;
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }

   private void SerializeDateTime(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group3));
      Group3 myGroup = new Group3();
      TextWriter writer = new StreamWriter(filename);

      ser.Serialize(writer, myGroup);
      writer.Close();
   }   
}

    

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

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.