XmlAttributes.XmlDefaultValue Propiedad

Definición

Obtiene o establece el valor predeterminado de un elemento o atributo XML.

C#
public object XmlDefaultValue { get; set; }
C#
public object? XmlDefaultValue { get; set; }

Valor de propiedad

Object

Object que representa el valor predeterminado de un elemento o atributo XML.

Ejemplos

En el ejemplo siguiente se muestra una clase denominada Pet que contiene un campo que tiene un valor predeterminado establecido en "Dog". Sin embargo, el ejemplo también crea un XmlAttributes objeto y establece su XmlDefaultValue propiedad en un nuevo valor predeterminado ("Cat"). Esto invalida el valor predeterminado original. Por lo tanto, si el valor del campo se establece en "Cat", el XmlSerializer lo trata como el valor predeterminado y no lo serializa. Si se establece en cualquier otro valor, serializa XmlSerializer el valor.

C#
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);
   }
}

Comentarios

Puede especificar el valor predeterminado de un elemento XML o un atributo XML aplicando un DefaultValueAttribute objeto a un miembro. Para examinar el resultado de aplicar el valor, compile la aplicación en un archivo DLL o ejecutable y pase el archivo resultante como argumento a la herramienta definición de esquema XML (XSD.exe). En el documento de esquema XML, se asigna un valor predeterminado al default atributo . En el ejemplo siguiente, el valor predeterminado del <Animal> elemento es "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>  

Para invalidar el valor predeterminado, cree y Object asígnelo a XmlDefaultValue.

Si el valor asignado a un campo o propiedad es igual al valor predeterminado de ese campo o propiedad, XmlSerializer no serializa el valor en la instancia XML. Esto se debe a que el valor asignado se puede recuperar del esquema XML. En otras palabras, establecer un campo o una propiedad en su propio valor predeterminado es equivalente a no establecerlo en absoluto. Del mismo modo, si no se establece ningún valor para el campo o propiedad, usa XmlSerializer el valor predeterminado que se encuentra en el esquema. En ambos casos, (establecer la propiedad en su valor predeterminado o no establecerla en absoluto), la instancia de documento XML no contiene ningún valor para la propiedad .

Puede usar los constructores de clase en lugar del esquema para asignar los valores predeterminados. Si usa Xsd.exe para generar clases a partir de esquemas, puede comentar o quitar todos los atributos [System.ComponentModel.DefaultValueAttribute("myFieldName")] de los archivos de clase.

Se aplica a

Produto Versións
.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
.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
.NET Standard 2.0, 2.1
UWP 10.0