2,754 次浏览

如何将 XML 的 XSD 定义转换为 C# 类

当我们将一些配置数据存储在 XML 文档中,或希望自定义某种 XML 格式的文档时,最好先去定义 XML 对应的 XSD 规范。定义 XSD 后,我们不仅可以在 VS 等 IDE 中对相应的 XML 文件的语法进行自动检查或属性匹配,同时也可以自动生成对应的实体类,简化 XML 的创建、修改以及读取。

打开 VS,在 XSD 文件上点击鼠标右键,点选 Open Command Prompt

然后在命令行中输入  xsd abc.xsd /classes ,随后就会在当前目录生成对应的 C# 类了,如果需要 VB 语言版本,追加 /language:vb 参数即可。(Tips: 键入  explorer .   就可以在 Windows Explorer 查看当前的目录)

左侧是 XSD 定义,右侧是自动生成的 C# 类。

我们可以编写一个简单的类,来完成实体对象和 XML 文件的读取与存储。

namespace SquirrelFramework.Configurations
{
    #region using directives
 
    using System.IO;
    using System.Xml.Serialization;
 
    #endregion using directives
 
    public class XmlManager<TXmlModel>
    {
        public string XmlFilePath { get; }
        public bool IsEnableFileWatcher { get; private set; }
        private XmlSerializer serializer;
        private FileSystemWatcher fileWatcher;
 
        public XmlManager(string xmlFilePath, bool isEnableFileWatcher = false)
        {
            this.XmlFilePath = xmlFilePath;
            this.serializer = new XmlSerializer(typeof(TXmlModel));
            this.IsEnableFileWatcher = isEnableFileWatcher;
        }
 
        public TXmlModel GetModel()
        {
            using (var stream = new FileStream(this.XmlFilePath, FileMode.OpenOrCreate, FileAccess.Read))
            {
                return (TXmlModel)this.serializer.Deserialize(stream);
            }
        }
 
        public void SaveModel(TXmlModel model)
        {
            using (var stream = new FileStream(this.XmlFilePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                this.serializer.Serialize(stream, model);
            }
        }
 
        public void EnableFileWatcher(FileSystemEventHandler fileSystemEventHandler)
        {
            if (this.fileWatcher != null)
            {
                this.fileWatcher.Dispose();
            }
            this.IsEnableFileWatcher = true;
            this.fileWatcher = new FileSystemWatcher
            {
                Path = Path.GetDirectoryName(this.XmlFilePath),
                IncludeSubdirectories = false,
                Filter = Path.GetFileName(this.XmlFilePath),
                //Filter = "*.config"
                EnableRaisingEvents = this.IsEnableFileWatcher
            };
            this.fileWatcher.Changed += fileSystemEventHandler;
        }
 
        public void DisableFileWatcher()
        {
            if (this.fileWatcher != null)
            {
                this.fileWatcher.Dispose();
            }
            this.IsEnableFileWatcher = false;
        }
    }
}

这样,在使用 XML 存储配置时,就可以对一个对象直接进行操作了,非常便捷,如果需要学习 XSD 的一些语法,可以阅读这篇教程

About nista

THERE IS NO FATE BUT WHAT WE MAKE.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注