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:\temp\SerializationOverview.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:\temp\SerializationOverview.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.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了