XmlAnyAttributeAttribute Constructor

Definition

Constructs a new instance of the XmlAnyAttributeAttribute class.

C#
public XmlAnyAttributeAttribute();

Examples

The following example constructs an XmlAnyAttributeAttribute that is used to override the deserialization of an object. 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>  
C#
using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

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

public class Test{
   static void Main(){
      Test t = new Test();
      t.DeserializeObject("UnknownAttributes.xml");
   }

   private void DeserializeObject(string filename){
      // Use the CreateOverrideSerializer to return an instance
      // of the XmlSerializer customized for overrides.
      XmlSerializer ser = CreateOverrideSerializer();
      // A FileStream is needed to read the XML document.
      FileStream fs = new FileStream(filename, FileMode.Open);
     Group g = (Group)
        ser.Deserialize(fs);
     fs.Close();
     Console.WriteLine(g.GroupName);
     Console.WriteLine(g.Things.Length);
     foreach(XmlAttribute xAtt in g.Things){
        Console.WriteLine(xAtt.Name + ": " + xAtt.InnerXml);
        }
   }

   private XmlSerializer CreateOverrideSerializer(){
      // Override the Things field to capture all
      // unknown XML attributes.
      XmlAnyAttributeAttribute myAnyAttribute = 
      new XmlAnyAttributeAttribute();
      XmlAttributeOverrides xOverride = 
      new XmlAttributeOverrides();
      XmlAttributes xAtts = new XmlAttributes();
      xAtts.XmlAnyAttribute=myAnyAttribute;
      xOverride.Add(typeof(Group), "Things", xAtts);
       
      return new XmlSerializer(typeof(Group) , xOverride);
   }
}

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0