zoukankan      html  css  js  c++  java
  • How to: Read Object Data from an XML File

    This example reads object data that was previously written to an XML file using the XmlSerializer class.

    Example

    This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more information, see Code Snippets.

    public class Book
    {
        public String title;
    }       
    
    public void ReadXML()
    {
        // First write something so that there is something to read ...
        var b = new Book { title = "Serialization Overview" };
        var writer = new System.Xml.Serialization.XmlSerializer(typeof(Book));
        var wfile = new System.IO.StreamWriter(@"c:	empSerializationOverview.xml");
        writer.Serialize(wfile, b);
        wfile.Close();
    
        // Now we can read the serialized book ...
        System.Xml.Serialization.XmlSerializer reader = 
            new System.Xml.Serialization.XmlSerializer(typeof(Book));
        System.IO.StreamReader file = new System.IO.StreamReader(
            @"c:	empSerializationOverview.xml");
        Book overview =  (Book)reader.Deserialize(file);
        file.Close();
    
        Console.WriteLine(overview.title);
    
    }

    Compiling the Code

    Replace the file name "c:IntroToVB.xml" with the name of the file containing the serialized data. For more information about serializing data, see How to: Write Object Data to an XML File (C# and Visual Basic).

    The class must have a public constructor without parameters.

    Only public properties and fields are deserialized.

    Robust Programming

    The following conditions may cause an exception:

    • The class being serialized does not have a public, parameterless constructor.

    • The data in the file does not represent data from the class to be deserialized.

    • The file does not exist (IOException).

    .NET Framework Security

    Always verify inputs, and never deserialize data from an untrusted source.

    The re-created object runs on a local computer with the permissions of the code that deserialized it.

    Verify all inputs before using the data in your application.

  • 相关阅读:
    POJ 3687 Labeling Balls()
    POJ 2777 Count Color(线段树之成段更新)
    POJ 1961 Period( KMP )*
    POJ 2406 Power Strings (KMP)
    hdu 2199 Can you solve this equation?(二分搜索)
    10679 多少个1
    POJ 2823 Sliding Window
    POJ 2299 Ultra-QuickSort(线段树入门)
    最短路径—Dijkstra算法和Floyd算法
    poj1125&zoj1082Stockbroker Grapevine(Floyd算法)
  • 原文地址:https://www.cnblogs.com/chucklu/p/5145586.html
Copyright © 2011-2022 走看看