XmlAnyAttributeAttribute Класс

Определение

Specifies that the member (a field that returns an array of XmlAttribute objects) can contain any XML attributes.Specifies that the member (a field that returns an array of XmlAttribute objects) can contain any XML attributes.

public ref class XmlAnyAttributeAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)]
public class XmlAnyAttributeAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)]
public class XmlAnyAttributeAttribute : Attribute
type XmlAnyAttributeAttribute = class
    inherit Attribute
Public Class XmlAnyAttributeAttribute
Inherits Attribute
Наследование
XmlAnyAttributeAttribute
Атрибуты

Примеры

В следующем примере все неизвестные атрибуты собираются в массив объектов XmlAttribute.The following example collects all unknown attributes into an array of XmlAttribute objects. Чтобы испытать пример, создайте файл с именем UnknownAttributes.xml, содержащий следующий код XML:To try the example, create a file named UnknownAttributes.xml that contains 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"   
GroupType = 'Technical' GroupNumber = '42' GroupBase = 'Red'>  
  <GroupName>MyGroup</GroupName>  
</Group>  
#using <System.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::Collections;
using namespace System::IO;
using namespace System::Xml::Serialization;
using namespace System::Xml;

public ref class Group
{
public:
   String^ GroupName;

   // The UnknownAttributes array will be used to collect all unknown
   // attributes found when deserializing.

   [XmlAnyAttributeAttribute]
   array<XmlAttribute^>^XAttributes;
};

void SerializeObject( String^ filename, Object^ g )
{
   XmlSerializer^ ser = gcnew XmlSerializer( Group::typeid );
   TextWriter^ writer = gcnew StreamWriter( filename );
   ser->Serialize( writer, g );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlSerializer^ ser = gcnew XmlSerializer( Group::typeid );

   // A FileStream is needed to read the XML document.
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Group^ g = safe_cast<Group^>(ser->Deserialize( fs ));
   fs->Close();

   // Write out the data, including unknown attributes.
   Console::WriteLine( g->GroupName );
   Console::WriteLine(  "Number of unknown attributes: {0}", g->XAttributes->Length );
   for ( IEnumerator ^ e = g->XAttributes->GetEnumerator(); e->MoveNext();  )
   {
      XmlAttribute^ xAtt = safe_cast<XmlAttribute^>(e->Current);
      Console::WriteLine( "{0}: {1}", xAtt->Name, xAtt->InnerXml );
   }
   SerializeObject( "AttributesAdded.xml", g );
}

int main()
{
   // Deserialize the file containing unknown attributes.
   DeserializeObject(  "UnknownAttributes.xml" );
}

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

public class Group{
   public string GroupName;
   // The UnknownAttributes array will be used to collect all unknown
   // attributes found when deserializing.
   [XmlAnyAttribute]
    public XmlAttribute[]XAttributes;
}

public class Test{
   static void Main(){
      Test t = new Test();
      // Deserialize the file containing unknown attributes.

      t.DeserializeObject("UnknownAttributes.xml");
   }

   private void DeserializeObject(string filename){
      XmlSerializer ser = new XmlSerializer(typeof(Group));
      // A FileStream is needed to read the XML document.
     FileStream fs = new FileStream(filename, FileMode.Open);
     Group g = (Group) ser.Deserialize(fs);
     fs.Close();
     // Write out the data, including unknown attributes.
     Console.WriteLine(g.GroupName);
     Console.WriteLine("Number of unknown attributes: " + 
     g.XAttributes.Length);
     foreach(XmlAttribute xAtt in g.XAttributes){
     Console.WriteLine(xAtt.Name + ": " + xAtt.InnerXml);
     }
     // Serialize the object again with the attributes added.
     this.SerializeObject("AttributesAdded.xml",g);
   }

   private void SerializeObject(string filename, object g){
      XmlSerializer ser = new XmlSerializer(typeof(Group));
      TextWriter writer = new StreamWriter(filename);
      ser.Serialize(writer, g);
      writer.Close();
   }
}
Imports System.IO
Imports System.Xml.Serialization
Imports System.Xml

Public Class Group
   Public GroupName As String 
   ' The UnknownAttributes array will be used to collect all unknown
   ' attributes found when deserializing.
   <XmlAnyAttribute> _
    Public UnknownAttributes()As XmlAttribute
End Class

Public Class Test
   Shared Sub Main()
      Dim t  As Test = New Test()
      ' Deserialize the file containing unknown attributes.
      t.DeserializeObject("UnknownAttributes.xml")
   End Sub

   Private Sub DeserializeObject(filename As String)
      Dim ser As XmlSerializer = New XmlSerializer(GetType(Group))
      ' A FileStream is needed to read the XML document.
     Dim fs As FileStream = New FileStream(filename, FileMode.Open)
     Dim g As Group = CType(ser.Deserialize(fs), Group)
     fs.Close()
     ' Write out the data, including unknown attributes.
     Console.WriteLine(g.GroupName)
     Console.WriteLine("Number of unknown attributes: " & _ 
     g.UnknownAttributes.Length)
     Dim xAtt As XmlAttribute
     for each xAtt in g.UnknownAttributes
        Console.WriteLine(xAtt.Name & ": " & xAtt.InnerXml)
     Next
     ' Serialize the object again with the attributes added.
     Me.SerializeObject("AttributesAdded.xml",g)
   End Sub

   Private Sub SerializeObject(filename As String, g As object)
      Dim ser As XmlSerializer = New XmlSerializer(GetType(Group))
      DIm writer As TextWriter = New StreamWriter(filename)
      ser.Serialize(writer, g)
      writer.Close()
   End Sub
End Class

Комментарии

Используйте XmlAnyAttributeAttribute, чтобы содержать произвольные данные (в виде атрибутов XML), которые отправляются как часть документа XML, например, метаданные, отправляемые в составе документа.Use the XmlAnyAttributeAttribute to contain arbitrary data (as XML attributes) that is sent as part of an XML document, such as, metadata sent as part of the document.

Примените XmlAnyAttributeAttribute к полю, которое возвращает массив объектов XmlAttribute или XmlNode.Apply the XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute or XmlNode objects. При вызове метода Deserialize класса XmlSerializer в массиве собираются все XML-атрибуты, не имеющие соответствующего члена в классе, который необходимо десериализовать.When the Deserialize method of the XmlSerializer class is called, all XML attributes that do not have a corresponding member in the class being deserialized are collected in the array. После десериализации можно выполнить итерацию по коллекции элементов XmlAttribute для обработки данных.After deserialization, you can iterate through the collection of XmlAttribute items to process the data.

События UnknownNode и UnknownAttribute XmlSerializer не выполняются при применении XmlAnyAttributeAttribute к члену класса.The UnknownNode and UnknownAttribute events of the XmlSerializer do not occur if you apply the XmlAnyAttributeAttribute to a member of a class.

Примечание

Вместо более длинного XmlAnyAttributeAttributeможно использовать слово XmlAnyAttribute в коде.You can use the word XmlAnyAttribute in your code instead of the longer XmlAnyAttributeAttribute.

Дополнительные сведения об использовании атрибутов см. в разделе атрибуты.For more information about using attributes, see Attributes.

Конструкторы

XmlAnyAttributeAttribute()

Constructs a new instance of the XmlAnyAttributeAttribute class.Constructs a new instance of the XmlAnyAttributeAttribute class.

Свойства

TypeId

When implemented in a derived class, gets a unique identifier for this Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Унаследовано от Attribute)

Методы

Equals(Object)

Returns a value that indicates whether this instance is equal to a specified object.Returns a value that indicates whether this instance is equal to a specified object.

(Унаследовано от Attribute)
GetHashCode()

Returns the hash code for this instance.Returns the hash code for this instance.

(Унаследовано от Attribute)
GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Унаследовано от Object)
IsDefaultAttribute()

When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Унаследовано от Attribute)
Match(Object)

When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Унаследовано от Object)

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.Maps a set of names to a corresponding set of dispatch identifiers.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can be used to get the type information for an interface.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.Provides access to properties and methods exposed by an object.

(Унаследовано от Attribute)

Применяется к

Дополнительно