共用方式為


HOW TO:從 XML 檔案讀取類別資料

更新:2007 年 11 月

這個範例會使用 XmlSerializer 類別的 Deserialize 方法,讀取 IntroToVCS.xml 範例檔案中某一物件內所儲存的資料。

範例

public class Book
{
    public string title;

    static void Main()
    {
        Book introToVCS  = new Book();
        System.Xml.Serialization.XmlSerializer reader = new
        System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

        // Read the XML file.
        System.IO.StreamReader file= 
            new System.IO.StreamReader("c:\\IntroToVCS.xml");

        // Deserialize the content of the file into a Book object.
        introToVCS = (Book) reader.Deserialize(file);
        System.Windows.Forms.MessageBox.Show(introToVCS.title,
            "Book Title");
    }
}

編譯程式碼

您可以直接於命令提示字元編譯這個範例,或是使用 Visual Studio IDE 將程式碼貼到主控台應用程式中。以第二種情況而言,您必須參考 System.Windows.Forms.dll 檔案。

穩固程式設計

以下情形可能會導致例外狀況:

  • 路徑名稱可能太長。

請參閱

概念

在 Visual C# 中設計使用者介面

其他資源

存取以及顯示資料

Visual C# 導覽