C#使用XML文件的操作詳解及示例
前言
XML是 Extensible Markup Language 的簡(jiǎn)稱,用于存儲(chǔ)和傳輸數(shù)據(jù)的可擴(kuò)展標(biāo)記語(yǔ)言。它被應(yīng)用在數(shù)據(jù)交換、數(shù)據(jù)存儲(chǔ)、Web服務(wù)、網(wǎng)絡(luò)協(xié)議等場(chǎng)景。
XML 具有可擴(kuò)展性、結(jié)構(gòu)化、標(biāo)準(zhǔn)化、簡(jiǎn)單易讀等幾個(gè)特點(diǎn)。
基本結(jié)構(gòu)
XML 基本結(jié)構(gòu)包括文檔聲明、根元素、子元素、屬性、注釋、處理指令等部分。
<?xml version="1.0" encoding="UTF-8"?> <根元素> <子元素 屬性="屬性值">內(nèi)容</子元素> <!-- 注釋內(nèi)容 --> <?處理指令 ?> </根元素>
文檔聲明
文檔聲明主要用于描述XML文檔的版本與編碼格式,每個(gè)文檔必須包含一個(gè)聲明,并在文檔開(kāi)頭。如下聲明:版本1.0 編碼格式為UTF-8。
<?xml version="1.0" encoding="UTF-8"?>
根元素
根元素包圍文檔中的所有數(shù)據(jù),是其它元素的根,每個(gè)文檔必須有一個(gè)根元素。如下示例:有一個(gè)configure根元素,其下有其它內(nèi)容。
<configure> <Description>Fountain WinForm App</Description> <Files> <File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" /> </Files> </configure>
子元素
子元素是文檔的基本單元,它包含屬性、內(nèi)容等元素。如下示例:
<name>Apple</name> <File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" />
屬性
元素可以有屬性,用于元素的額外信息。它在開(kāi)始標(biāo)簽中定義,以名稱/鍵值對(duì)的形式出現(xiàn)。如下示例:File 元素存在Version、Name、DateTime屬性。
<File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" />
注釋
注釋為文檔中添加注釋或說(shuō)明,以<!--開(kāi)始,以-->結(jié)束。如下示例:
<configure> <Description>Fountain WinForm App</Description> <Files> <!-- 程序的所文件名稱、版本、更新日期 --> <File Version="1.2.11.0" Name="log4net.dll" DateTime="2023-4-26" /> </Files> </configure>
處理指令
處理指令提供了關(guān)于XML處理器如何處理文檔的指令。如下示例:標(biāo)識(shí) 文檔的樣式表。
<?xml-stylesheet type="text/xsl" href="sample.xsl" rel="external nofollow" ?>
命名空間
用于定義文檔中元素和屬性的范圍和作用域的機(jī)制。
文檔操作
通過(guò)System.XML命名空間中的類可以完成常用的操作。下表為操作XML文檔相關(guān)的類。
類 | 描述 |
---|---|
XmlDocument | 創(chuàng)建、修改及保存XML文檔。 |
XmlNode | 表示 XML 文檔中的單個(gè)節(jié)點(diǎn) |
XmlElement | 訪問(wèn)元素的名稱、屬性和子元素。 |
XmlTextWriter | 提供快速、非緩存的寫入器。 |
XPathDocument | 提供只讀形式讀取XML文檔。 |
XPathNavigator | 提供瀏覽、提取XML節(jié)點(diǎn) 數(shù)據(jù) |
XmlAttribute | 訪問(wèn)XML屬性的名稱和值 |
XmlText | 訪問(wèn)文本內(nèi)容 |
創(chuàng)建文檔
通過(guò) XmlDocument 的 CreateXmlDeclaration 對(duì) XML 文檔進(jìn)行聲明,再通過(guò) CreateElement 創(chuàng)建 XML 元素,最后保存 XML 文件。下面通過(guò)代碼進(jìn)一步了解 XML 文檔的創(chuàng)建。
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> /// 創(chuàng)建文檔 /// </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); //創(chuàng)建根元素 XmlElement rootNode = xmlDocument.CreateElement("configure"); xmlDocument.AppendChild(rootNode); // 創(chuàng)建 Description 子元素 XmlElement descSubElement = xmlDocument.CreateElement("Description"); //元素內(nèi)容 descSubElement.InnerText = "Fountain WinForm App"; rootNode.AppendChild(descSubElement); // 創(chuàng)建 Updater 子元素 XmlElement updaterSubElement = xmlDocument.CreateElement("Updater"); rootNode.AppendChild(updaterSubElement); // 創(chuàng)建 url 子元素 XmlElement urlSubElement = xmlDocument.CreateElement("url"); //中間文本 urlSubElement.InnerText = "http://127.0.0.1/update"; // 添加到父結(jié)點(diǎn) updaterSubElement.AppendChild(urlSubElement); XmlElement versionSubElement = xmlDocument.CreateElement("Version"); //中間文本 versionSubElement.InnerText = "3.8.0.24043"; // 添加到父結(jié)點(diǎn) updaterSubElement.AppendChild(versionSubElement); // 創(chuàng)建 Files 子元素 XmlElement filesSubElement = xmlDocument.CreateElement("Files"); rootNode.AppendChild(filesSubElement); // 創(chuàng)建 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); } } } }
運(yùn)行結(jié)果:
<?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>
讀取文檔
通過(guò) XmlDocument 的 Load 對(duì) XML 文檔進(jìn)行加載XML文件,然后通過(guò) SelectSingleNode 得到指定的節(jié)點(diǎn)元素,再通過(guò) GetAttribute 得到具體的屬性值。下面通過(guò)代碼進(jìn)一步了解 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")); // 獲取 Files XmlNode XmlNode = xmlDocument.SelectSingleNode("configure"); // 得到根節(jié)點(diǎn)的所有子節(jié)點(diǎn) XmlNodeList xmlNodeList = XmlNode.ChildNodes; StringBuilder stringBuilder = new StringBuilder(); // 循環(huán)讀取 foreach (XmlNode xmlNode in xmlNodeList) { // 判斷節(jié)點(diǎn)是否有子節(jié)點(diǎn) 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); } } } }
運(yùn)行結(jié)果:
#text:Fountain WinForm App
url:http://127.0.0.1/update
Version:3.8.0.24043
File:
File: 屬性Version=1.2.11.0
File: 屬性Name=log4net.dll
File: 屬性DateTime=2024-04-13
修改文檔
通過(guò) XmlDocument 的 Load 對(duì) XML 文檔進(jìn)行加載XML文件,然后讀取到元素節(jié)點(diǎn),對(duì)元素節(jié)點(diǎn)進(jìn)行刪除、變屬性值、元素文本等,最后保存 XML 文件。下面通過(guò)代碼進(jìn)一步了解 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 元素節(jié)點(diǎn) xmlNodeUpdate.RemoveChild(xmlMainInfo); break; } } } // 循環(huán)讀取 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)) { // 修改元素節(jié)點(diǎn)屬性 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); } } } }
運(yùn)行結(jié)果:
<?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>
小結(jié)
以上 XML 文檔相關(guān)內(nèi)容及在C#中如何實(shí)現(xiàn)對(duì)文件創(chuàng)建、修改、讀取的操作。希望能幫助大家對(duì)XML的應(yīng)用有一定的參考作用。 對(duì) XML 的創(chuàng)建、修改、讀取也有其它方式。后續(xù)對(duì)其介紹。
到此這篇關(guān)于C#使用XML文件的操作詳解及示例的文章就介紹到這了,更多相關(guān)C#使用XML文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)動(dòng)態(tài)生成靜態(tài)頁(yè)面的類詳解
這篇文章主要介紹了C#實(shí)現(xiàn)動(dòng)態(tài)生成靜態(tài)頁(yè)面的類,結(jié)合實(shí)例形式詳細(xì)分析了C#動(dòng)態(tài)生成靜態(tài)頁(yè)面的原理與相關(guān)使用技巧,需要的朋友可以參考下2016-04-04C#基于自定義事件EventArgs實(shí)現(xiàn)發(fā)布訂閱模式
這篇文章介紹了C#基于自定義事件EventArgs實(shí)現(xiàn)發(fā)布訂閱模式的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05C#將DataGridView中的數(shù)據(jù)保存到CSV和Excel中
這篇文章介紹了C#將DataGridView中的數(shù)據(jù)保存到CSV和Excel中的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04C#實(shí)現(xiàn)根據(jù)數(shù)字序號(hào)輸出星期幾的簡(jiǎn)單實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)數(shù)字序號(hào)輸出星期幾的簡(jiǎn)單實(shí)例,代碼簡(jiǎn)潔實(shí)用,也有助于初學(xué)者更好的理解C#的switch和if語(yǔ)句的流程控制,需要的朋友可以參考下2014-07-07C#實(shí)現(xiàn)壓縮和解壓縮的方法示例【Gzip和Zip方式】
這篇文章主要介紹了C#實(shí)現(xiàn)壓縮和解壓縮的方法,結(jié)合具體實(shí)例形式分析了Gzip和Zip兩種壓縮操作實(shí)現(xiàn)方法,需要的朋友可以參考下2017-06-06