How to: Write Object Data to an XML File
This example writes the object from a class to an XML file using the XmlSerializer class.
Namespace: System.Xml.Serialization
Assembly: System.Xml (in System.Xml.dll)
Example
This code example defines a class named Book, creates an instance of the class, and uses XML serialization to write the instance to an XML file.
Code similar to this is available as an IntelliSense code snippet. In the Code Snippet Manager, it is located in XML. For more information, see Code Snippets.
public class XMLWrite { static void Main(string[] args) { WriteXML(); } public class Book { public String title; } public static void WriteXML() { Book overview = new Book(); overview.title = "Serialization Overview"; System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Book)); var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//SerializationOverview.xml"; System.IO.FileStream file = System.IO.File.Create(path); writer.Serialize(file, overview); file.Close(); } }
Compiling the Code
The class must have a public constructor without parameters.
Robust Programming
The following conditions may cause an exception:
-
The class being serialized does not have a public, parameterless constructor.
-
The file exists and is read-only (IOException).
-
The path is too long (PathTooLongException).
-
The disk is full (IOException).
.NET Framework Security
This example creates a new file, if the file does not already exist.
If an application needs to create a file, that application needs Create access for the folder.
If the file already exists, the application needs only Write access, a lesser privilege.
Where possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create access for a folder.
作者: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:你的「微服务管家」又秀新绝活了