XML是 Extensible Markup Language 的简称,用于存储和传输数据的可扩展标记语言。它被应用在数据交换、数据存储、Web服务、网络协议等场景。
XML 具有可扩展性、结构化、标准化、简单易读等几个特点。
基本结构
XML 基本结构包括文档声明、根元素、子元素、属性、注释、处理指令等部分。
<?xml version="1.0" encoding="UTF-8"?><根元素><子元素 属性="属性值">内容</子元素><!-- 注释内容 --><?处理指令 ?></根元素>
文档声明
文档声明主要用于描述XML文档的版本与编码格式,每个文档必须包含一个声明,并在文档开头。如下声明:版本1.0 编码格式为UTF-8。
<?xml version="1.0" encoding="UTF-8"?>
根元素
根元素包围文档中的所有数据,是其它元素的根,每个文档必须有一个根元素。如下示例:有一个configure根元素,其下有其它内容。
<configure><Description>Fountain WinForm App</Description><Files><File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" /></Files></configure>
子元素
子元素是文档的基本单元,它包含属性、内容等元素。如下示例:
<name>Apple</name><File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" />
属性
元素可以有属性,用于元素的额外信息。它在开始标签中定义,以名称/键值对的形式出现。如下示例:File 元素存在Version、Name、DateTime属性。
<File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" />
注释
注释为文档中添加注释或说明,以<!--开始,以-->结束。如下示例:
<configure><Description>Fountain WinForm App</Description><Files><!-- 程序的所文件名称、版本、更新日期 --><File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" /></Files></configure>
处理指令
处理指令提供了关于XML处理器如何处理文档的指令。如下示例:标识 文档的样式表。
<?xml-stylesheet type="text/xsl" href="sample.xsl"?>
命名空间
用于定义文档中元素和属性的范围和作用域的机制。
文档操作
通过System.XML命名空间中的类可以完成常用的操作。下表为操作XML文档相关的类。
| 类 | 描述 |
|---|---|
| XmlDocument | 创建、修改及保存XML文档。 |
| XmlNode | 表示 XML 文档中的单个节点 |
| XmlElement | 访问元素的名称、属性和子元素。 |
| XmlTextWriter | 提供快速、非缓存的写入器。 |
| XPathDocument | 提供只读形式读取XML文档。 |
| XPathNavigator | 提供浏览、提取XML节点 数据 |
| XmlAttribute | 访问XML属性的名称和值 |
| XmlText | 访问文本内容 |
创建文档
通过 XmlDocument 的 CreateXmlDeclaration 对 XML 文档进行声明,再通过 CreateElement 创建 XML 元素,最后保存 XML 文件。下面通过代码进一步了解 XML 文档的创建。
using System;using System.IO;using System.Windows.Forms;using System.Xml;namespace Fountain.WinForm.XMLDemo{public partial class XMLDemoForm : Form{public XMLDemoForm(){InitializeComponent();}/// <summary>/// 创建文档/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void ButtonCreate_Click(object sender, EventArgs e){try{XmlDocument xmlDocument = new XmlDocument();// XML声明XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes");xmlDocument.AppendChild(xmlDeclaration);//创建根元素XmlElement rootNode = xmlDocument.CreateElement("configure");xmlDocument.AppendChild(rootNode);// 创建 Description 子元素XmlElement descSubElement = xmlDocument.CreateElement("Description");//元素内容descSubElement.InnerText = "Fountain WinForm App";rootNode.AppendChild(descSubElement);// 创建 Updater 子元素XmlElement updaterSubElement = xmlDocument.CreateElement("Updater");rootNode.AppendChild(updaterSubElement);// 创建 url 子元素XmlElement urlSubElement = xmlDocument.CreateElement("url");//中间文本urlSubElement.InnerText = "http://127.0.0.1/update";// 添加到父结点updaterSubElement.AppendChild(urlSubElement);XmlElement versionSubElement = xmlDocument.CreateElement("Version");//中间文本versionSubElement.InnerText = "3.8.0.24043";// 添加到父结点updaterSubElement.AppendChild(versionSubElement);// 创建 Files 子元素XmlElement filesSubElement = xmlDocument.CreateElement("Files");rootNode.AppendChild(filesSubElement);// 创建 File 子元素XmlElement fileSubElement = xmlDocument.CreateElement("File");// 属性fileSubElement.SetAttribute("Version", "1.2.11.0");fileSubElement.SetAttribute("Name", "log4net.dll");fileSubElement.SetAttribute("DateTime", DateTime.Now.ToString("yyyy-MM-dd"));filesSubElement.AppendChild(fileSubElement);// 保存文档xmlDocument.Save(string.Format("{0}{1}{2}", Application.StartupPath,Path.DirectorySeparatorChar, "Version.xml"));}catch (Exception ex){MessageBox.Show(ex.Message);}}}}
运行结果:
<?xml version="1.0" encoding="utf-8" standalone="yes"?><configure><Description>Fountain WinForm App</Description><Updater><url>http://127.0.0.1/update</url><Version>3.8.0.24043</Version></Updater><Files><File Version="1.2.11.0" Name="log4net.dll" DateTime="2024-04-13" /></Files></configure>
读取文档
通过 XmlDocument 的 Load 对 XML 文档进行加载XML文件,然后通过 SelectSingleNode 得到指定的节点元素,再通过 GetAttribute 得到具体的属性值。下面通过代码进一步了解 XML 文档的读取。
using System;using System.IO;using System.Text;using System.Windows.Forms;using System.Xml;namespace Fountain.WinForm.XMLDemo{public partial class XMLDemoForm : Form{public XMLDemoForm(){InitializeComponent();}/// <summary>/// 读取文档/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void ButtonRead_Click(object sender, EventArgs e){try{XmlDocument xmlDocument = new XmlDocument();xmlDocument.Load(string.Format("{0}{1}{2}", Application.StartupPath, Path.DirectorySeparatorChar, "Version.xml"));// 获取 FilesXmlNode XmlNode = xmlDocument.SelectSingleNode("configure");// 得到根节点的所有子节点XmlNodeList xmlNodeList = XmlNode.ChildNodes;StringBuilder stringBuilder = new StringBuilder();// 循环读取foreach (XmlNode xmlNode in xmlNodeList){// 判断节点是否有子节点if (xmlNode.ChildNodes.Count>0){foreach (XmlNode subXmlNode in xmlNode.ChildNodes){stringBuilder.AppendLine(string.Format("{0}:{1}", subXmlNode.Name, subXmlNode.InnerText));// 读取元素属性if (subXmlNode.Attributes!=null && subXmlNode.Attributes.Count>0){for (int i = 0; i < subXmlNode.Attributes.Count;i++){stringBuilder.AppendLine(string.Format("{0}:{1} 属性{2}={3}",subXmlNode.Name,subXmlNode.InnerText,subXmlNode.Attributes[i].Name,subXmlNode.Attributes[i].Value));}}}continue;}stringBuilder.AppendLine(string.Format("{0}:{1}", xmlNode.Name,xmlNode.InnerText));}// MessageBox.Show(stringBuilder.ToString());Console.WriteLine(stringBuilder.ToString());}catch (Exception ex){MessageBox.Show(ex.Message);}}}}
运行结果:
#text:Fountain WinForm Appurl:http://127.0.0.1/updateVersion:3.8.0.24043File:File: 属性Version=1.2.11.0File: 属性Name=log4net.dllFile: 属性DateTime=2024-04-13
修改文档
通过 XmlDocument 的 Load 对 XML 文档进行加载XML文件,然后读取到元素节点,对元素节点进行删除、变属性值、元素文本等,最后保存 XML 文件。下面通过代码进一步了解 XML 文档的修改。
using System;using System.IO;using System.Text;using System.Windows.Forms;using System.Xml;namespace Fountain.WinForm.XMLDemo{public partial class XMLDemoForm : Form{public XMLDemoForm(){InitializeComponent();}/// <summary>/// 修改文档/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void ButtonModify_Click(object sender, EventArgs e){try{XmlDocument xmlDocument = new XmlDocument();xmlDocument.Load(string.Format("{0}{1}{2}", Application.StartupPath, Path.DirectorySeparatorChar, "Version.xml"));// 获取根元素XmlNode rootNode = xmlDocument.DocumentElement;// 获取主信息XmlNodeList xmlNodeList = rootNode.SelectNodes("Updater");foreach (XmlNode xmlNodeUpdate in xmlNodeList){XmlNodeList xmlNodeMainInfo = xmlNodeUpdate.ChildNodes;foreach (XmlNode xmlMainInfo in xmlNodeMainInfo){if ("url".Equals(xmlMainInfo.Name,StringComparison.OrdinalIgnoreCase)){// 删除 url 元素节点xmlNodeUpdate.RemoveChild(xmlMainInfo);break;}}}// 循环读取foreach (XmlNode xmlNode in xmlNodeList){if (xmlNode.ChildNodes.Count > 0){foreach (XmlNode subXmlNode in xmlNode.ChildNodes){if (subXmlNode.Attributes != null && subXmlNode.Attributes.Count > 0){for (int i = 0; i < subXmlNode.Attributes.Count; i++){if ("DateTime".Equals(subXmlNode.Attributes[i].Name,StringComparison.OrdinalIgnoreCase)){// 修改元素节点属性subXmlNode.Attributes[i].Value = DateTime.Now.ToString("yyyy-MM-dd");}}}}continue;}}xmlDocument.Save(string.Format("{0}{1}{2}", Application.StartupPath, Path.DirectorySeparatorChar, "Version.xml"));}catch (Exception ex){MessageBox.Show(ex.Message);}}}}
运行结果:
<?xml version="1.0" encoding="utf-8" standalone="yes"?><configure><Description>Fountain WinForm App</Description><Updater><Version>3.8.0.24043</Version></Updater><Files><File Version="1.2.11.0" Name="log4net.dll" DateTime="2024-04-13" /></Files></configure>
小结
以上 XML 文档相关内容及在C#中如何实现对文件创建、修改、读取的操作。希望能帮助大家对XML的应用有一定的参考作用。 对 XML 的创建、修改、读取也有其它方式。后续对其介绍。