Share via


XmlAttributes.XmlDefaultValue 속성

정의

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

속성 값

Object

XML 요소 또는 특성의 기본값을 나타내는 Object입니다.

예제

다음 예제에서는 라는 클래스를 보여 줍니다. Pet "Dog"로 설정 된 기본 값이 있는 필드를 포함 하는 합니다. 그러나 예제에서는 XmlAttributes 개체 집합과 해당 XmlDefaultValue 속성을 새 기본 값 ("고양이"). 이 원래 기본값을 재정의합니다. 따라서 필드 값 "고양이"로 설정 된 경우는 XmlSerializer 기본 값으로 간주 하 고 serialize 되지 않습니다. 다른 값으로 설정 된 경우는 XmlSerializer 값을 serialize 합니다.

#using <System.dll>
#using <System.Xml.dll>

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

// This is the class that will be serialized. 
public ref class Pet
{
public:

   // The default value for the Animal field is "Dog". 

   [DefaultValueAttribute("Dog")]
   String^ Animal;
};

// Return an XmlSerializer used for overriding. 
XmlSerializer^ CreateOverrider()
{
   // Create the XmlAttributeOverrides and XmlAttributes objects. 
   XmlAttributeOverrides^ xOver = gcnew XmlAttributeOverrides;
   XmlAttributes^ xAttrs = gcnew 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( Pet::typeid, "Animal", xAttrs );

   // Create the XmlSerializer and return it.
   return gcnew XmlSerializer( Pet::typeid,xOver );
}

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

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

   // Create an instance of the class that will be serialized. 
   Pet^ myPet = gcnew 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();
}

void DeserializeObject( String^ filename )
{
   XmlSerializer^ mySerializer = CreateOverrider();
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Pet^ myPet = dynamic_cast<Pet^>(mySerializer->Deserialize( fs ));
   Console::WriteLine( myPet->Animal );
}

int main()
{
   SerializeObject( "OverrideDefaultValue.xml" );
   DeserializeObject( "OverrideDefaultValue.xml" );
}
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

설명

적용 하 여 XML 요소 또는 XML 특성의 기본값을 지정할 수는 DefaultValueAttribute 멤버입니다. 값에 적용 한 결과 검사 하려면 애플리케이션 DLL 이나 실행 파일을 컴파일하고 XML 스키마 정의 도구 (XSD.exe)를 파일에 인수로 전달 합니다. 기본값을 할당할 XML 스키마 문서에는 default 특성입니다. 다음 예제에서 요소의 기본값 <Animal> 은 "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>  

기본값을 재정의 하려면 만들기를 Object 에 할당 하는 XmlDefaultValue합니다.

필드 또는 속성에 할당 된 값은 해당 필드 또는 속성에 대 한 기본 값과 같은 경우는 XmlSerializer XML 인스턴스에 값을 serialize 하지 않습니다. 즉, XML 스키마에서 할당 된 값을 복구할 수 있습니다. 즉, 필드 또는 속성 자체 기본값으로 설정은 전혀 설정 하지 않은 경우에 해당 합니다. 마찬가지로 값이 없는 필드 또는 속성에 대해 설정 된 경우는 XmlSerializer 사용 스키마에서 기본 값을 찾을 수 있습니다. 둘 다의 경우, (기본값인 속성을 설정 또는 전혀 설정 하지 않은 경우)의 XML 문서 인스턴스에서 속성 값을 들어 있지 않습니다.

기본 값을 할당 하는 스키마 대신 클래스 생성자를 사용할 수 있습니다. Xsd.exe를 사용 하 여 스키마에서 클래스를 생성 하는, 하는 경우 주석 수도 있고 클래스 파일에서 [System.ComponentModel.DefaultValueAttribute("myFieldName")] 특성을 모두 제거할 수 있습니다.

적용 대상