共用方式為


XmlRootAttribute.IsNullable 屬性

定義

取得或設定一個值,指示是否XmlSerializer必須將設定為 的null成員序列化為設定為 的屬性truexsi:nil

public:
 property bool IsNullable { bool get(); void set(bool value); };
public bool IsNullable { get; set; }
member this.IsNullable : bool with get, set
Public Property IsNullable As Boolean

屬性值

true若 產生XmlSerializer屬性xsi:nil;否則 。 false

範例

以下範例序列化一個名為 Group的類別。 範例將 應用 XmlRootAttribute 於類別,並將性質設 IsNullablefalse

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

// Apply the XmlRootAttribute and set the IsNullable property to false.
[XmlRoot(IsNullable = false)]
public class Group
{
   public string Name;
}

public class Run
{
   public static void Main()
   {
   Console.WriteLine("Running");
      Run test = new Run();
      test.SerializeObject("NullDoc.xml");
   }

   public void SerializeObject(string filename)
   {
      XmlSerializer s = new XmlSerializer(typeof(Group));

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

      // Create the object to serialize.
      Group mygroup = null;

      // Serialize the object, and close the TextWriter.
      s.Serialize(writer, mygroup);
      writer.Close();
   }
}
Imports System.IO
Imports System.Xml.Serialization
Imports System.Xml


' Apply the XmlRootAttribute and set the IsNullable property to false.
<XmlRoot(IsNullable := False)> _
Public Class Group
    Public Name As String
End Class


Public Class Run
    
    Public Shared Sub Main()
        Console.WriteLine("Running")
        Dim test As New Run()
        test.SerializeObject("NullDoc.xml")
    End Sub     
    
    Public Sub SerializeObject(ByVal filename As String)
        Dim s As New XmlSerializer(GetType(Group))
        
        ' Writing the file requires a TextWriter.
        Dim writer As New StreamWriter(filename)
        
        ' Create the object to serialize.
        Dim mygroup As Group = Nothing
        
        ' Serialize the object, and close the TextWriter.
        s.Serialize(writer, mygroup)
        writer.Close()
    End Sub
End Class

備註

結構的 XML 結構規範允許 XML 文件明確表示元素內容缺失。 此類元素包含設定為 true的屬性xsi:nil。 欲了解更多資訊,請參閱 XML 架構第一部分:結構第二版

若屬性 IsNullable 設定為 truexsi:nil 屬性會如以下 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" xsi:nil="true" />

IsNullable 屬性為 false,則會產生一個空元素,如下程式碼所示:

<?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" />

適用於