Partager via


XmlAttributes.XmlDefaultValue Propriété

Définition

Obtient ou définit la valeur par défaut d’un élément ou d’un attribut XML.

public:
 property System::Object ^ XmlDefaultValue { System::Object ^ get(); void set(System::Object ^ value); };
public object XmlDefaultValue { get; set; }
public object? XmlDefaultValue { get; set; }
member this.XmlDefaultValue : obj with get, set
Public Property XmlDefaultValue As Object

Valeur de propriété

Qui Object représente la valeur par défaut d’un élément ou d’un attribut XML.

Exemples

L’exemple suivant montre une classe nommée Pet qui contient un champ dont la valeur par défaut est définie sur « Dog ». Toutefois, l’exemple crée également un XmlAttributes objet et définit sa XmlDefaultValue propriété sur une nouvelle valeur par défaut (« Cat »). Cela remplace la valeur par défaut d’origine. Par conséquent, si la valeur du champ est définie sur « Cat », la XmlSerializer traite comme la valeur par défaut et ne la sérialise pas. Si elle est définie sur une autre valeur, la XmlSerializer sérialise la valeur.

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

// This is the class that will be serialized.
public class Pet
{
   // The default value for the Animal field is "Dog".
   [DefaultValueAttribute("Dog")]
   public string Animal ;
}

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeObject("OverrideDefaultValue.xml");
      test.DeserializeObject("OverrideDefaultValue.xml");
   }

   // Return an XmlSerializer used for overriding.
   public XmlSerializer CreateOverrider()
   {
      // Create the XmlAttributeOverrides and XmlAttributes objects.
      XmlAttributeOverrides xOver = new XmlAttributeOverrides();
      XmlAttributes xAttrs = new XmlAttributes();

      // Add an override for the default value of the GroupName.
      Object defaultAnimal= "Cat";
      xAttrs.XmlDefaultValue = defaultAnimal;

      // Add all the XmlAttributes to the XmlAttributeOverrides object.
      xOver.Add(typeof(Pet), "Animal", xAttrs);

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

   public void SerializeObject(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer mySerializer = CreateOverrider();

      // Writing the file requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);

      // Create an instance of the class that will be serialized.
      Pet myPet = new Pet();

      /* Set the Animal property. If you set it to the default value,
         which is "Cat" (the value assigned to the XmlDefaultValue
         of the XmlAttributes object), no value will be serialized.
         If you change the value to any other value (including "Dog"),
         the value will be serialized.
      */
      // The default value "Cat" will be assigned (nothing serialized).
      myPet.Animal= "";
      // Uncommenting the next line also results in the default
      // value because Cat is the default value (not serialized).
      //  myPet.Animal = "Cat";

      // Uncomment the next line to see the value serialized:
      // myPet.Animal = "fish";
      // This will also be serialized because Dog is not the
      // default anymore.
      //  myPet.Animal = "Dog";
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myPet);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlSerializer mySerializer = CreateOverrider();
      FileStream fs = new FileStream(filename, FileMode.Open);
      Pet myPet= (Pet)mySerializer.Deserialize(fs);
      Console.WriteLine(myPet.Animal);
   }
}
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports System.ComponentModel


' This is the class that will be serialized. 
Public Class Pet
    ' The default value for the Animal field is "Dog". 
    <DefaultValueAttribute("Dog")> Public Animal As String 
End Class


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("OverrideDefaultValue.xml")
        test.DeserializeObject("OverrideDefaultValue.xml")
    End Sub
    
    
    ' Return an XmlSerializer used for overriding. 
    Public Function CreateOverrider() As XmlSerializer
        ' Create the XmlAttributeOverrides and XmlAttributes objects. 
        Dim xOver As New XmlAttributeOverrides()
        Dim xAttrs As New XmlAttributes()
        
        ' Add an override for the default value of the GroupName. 
        Dim defaultName As Object = "Cat"
        xAttrs.XmlDefaultValue = defaultName
        
        ' Add all the XmlAttributes to the XmlAttributeOverrides object. 
        xOver.Add(GetType(Pet), "Animal", xAttrs)
        
        ' Create the XmlSerializer and return it.
        Return New XmlSerializer(GetType(Pet), xOver)
    End Function
    
    
    Public Sub SerializeObject(ByVal filename As String)
       ' Create an instance of the XmlSerializer class.
       Dim mySerializer As XmlSerializer = CreateOverrider()
        
       ' Writing the file requires a TextWriter.
       Dim writer As New StreamWriter(filename)
        
       ' Create an instance of the class that will be serialized. 
       Dim myPet As New Pet()
        
       ' Set the Animal property. If you set it to the default value,
       ' which is "Cat" (the value assigned to the XmlDefaultValue
       ' of the XmlAttributes object), no value will be serialized.
       ' If you change the value to any other value (including "Dog"),
       ' the value will be serialized.

      ' The default value "Cat" will be assigned (nothing serialized).
      myPet.Animal = ""
      ' Uncommenting the next line also results in the default 
      ' value because Cat is the default value (not serialized).
      '  myPet.Animal = "Cat"; 
      
      ' Uncomment the next line to see the value serialized:
      ' myPet.Animal = "fish";
      ' This will also be serialized because Dog is not the 
      ' default anymore.
      '  myPet.Animal = "Dog";
       ' Serialize the class, and close the TextWriter.
        mySerializer.Serialize(writer, myPet)
        writer.Close()
    End Sub
    
    
    Public Sub DeserializeObject(ByVal filename As String)
        Dim mySerializer As XmlSerializer = CreateOverrider()
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim myPet As Pet = CType(mySerializer.Deserialize(fs), Pet)
        Console.WriteLine(myPet.Animal)
    End Sub
End Class

Remarques

Vous pouvez spécifier la valeur par défaut d’un élément XML ou d’un attribut XML en appliquant un DefaultValueAttribute membre. Pour examiner le résultat de l’application de la valeur, compilez l’application dans une DLL ou un exécutable, puis transmettez le fichier résultant en tant qu’argument à l’outil XML Schema Definition (XSD.exe). Dans le document de schéma XML, une valeur par défaut est affectée à l’attribut default . Dans l’exemple suivant, la valeur par défaut de l’élément <Animal> est « Dogs ».

<?xml version="1.0"?>
 <schema attributeFormDefault="qualified"
 elementFormDefault="qualified" targetNamespace=""
 xmlns="http://www.w3.org/2000/10/XMLSchema">
   <element name="Pets" nullable="true" type="Pets"/>
   <complexType name="Pets">
     <sequence>
       <element default="Dogs" name="Animal" nullable="true"
        type="string" minOccurs="0"/>
     </sequence>
   </complexType>
 </schema>

Pour remplacer la valeur par défaut, créez-la Object et affectez-la à l’objet XmlDefaultValue.

Si la valeur affectée à un champ ou à une propriété est égale à la valeur par défaut de ce champ ou de cette propriété, elle XmlSerializer ne sérialise pas la valeur vers l’instance XML. Cela est dû au fait que la valeur affectée peut être récupérée à partir du schéma XML. En d’autres termes, la définition d’un champ ou d’une propriété sur sa propre valeur par défaut équivaut à ne pas la définir du tout. De même, si aucune valeur n’est définie pour le champ ou la propriété, elle XmlSerializer utilise la valeur par défaut trouvée dans le schéma. Dans les deux cas, (définition de la propriété sur sa valeur par défaut, ou ne la définissant pas du tout), l’instance de document XML ne contient aucune valeur pour la propriété.

Vous pouvez utiliser les constructeurs de classe au lieu du schéma pour affecter les valeurs par défaut. Si vous utilisez Xsd.exe pour générer des classes à partir de schémas, vous pouvez commenter ou supprimer tous les attributs [System.ComponentModel.DefaultValueAttribute(« myFieldName »)] des fichiers de classe.

S’applique à