XmlAnyAttributeAttribute Класс

Определение

Указывает, что член (поле, возвращающее массив объектов XmlAttribute) может содержать любые атрибуты XML.

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

Примеры

В следующем примере все неизвестные атрибуты собираются в массив XmlAttribute объектов . Чтобы попробовать пример, создайте файл с именем UnknownAttributes.xml , содержащий следующий 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-документа, например метаданные, отправляемые как часть документа.

Примените XmlAnyAttributeAttribute к полю, которое возвращает массив XmlAttribute объектов или XmlNode . При вызове Deserialize метода класса все XML-атрибуты, не имеющие соответствующего члена в десериализуемом XmlSerializer классе, собираются в массиве. После десериализации можно выполнить итерацию по коллекции XmlAttribute элементов для обработки данных.

События UnknownNodeXmlSerializer и UnknownAttribute не возникают, если применить XmlAnyAttributeAttribute к члену класса.

Примечание

В коде можно использовать слово XmlAnyAttribute вместо более длинного XmlAnyAttributeAttribute.

Дополнительные сведения об использовании атрибутов см. в разделе Атрибуты.

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

XmlAnyAttributeAttribute()

Конструирует новый экземпляр класса XmlAnyAttributeAttribute.

Свойства

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

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

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

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

Возвращает хэш-код данного экземпляра.

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

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

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

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

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

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

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

Создает неполную копию текущего объекта Object.

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

Возвращает строку, представляющую текущий объект.

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

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

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

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

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

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

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

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

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

Предоставляет доступ к открытым свойствам и методам объекта.

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

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

См. также раздел