您好,登錄后才能下訂單哦!
這篇“C#讀寫xml文件的方法是什么”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“C#讀寫xml文件的方法是什么”文章吧。
1。我認為是最原始,最基本的一種:利用XmlDocument向一個XML文件里寫節點,然后再利用XmlDocument保存文件。
首先加載要寫入的XML文件,但是如果沒有的,就要新建,在新建的過程中,要有寫入的代碼;
XmlDocument doc = new XmlDocument(); try { doc.Load("new.xml"); } catch { XmlTextWriter xtw = new XmlTextWriter("new.xml", Encoding.UTF8); //新建XML文件 xtw.WriteStartDocument(); xtw.WriteStartElement("gnode"); // gnode根節點 xtw.WriteStartElement("myxm1"); // gnode根節點下的元素myxmls xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Close(); doc.Load("new.xml"); } XmlNode xn = doc.DocumentElement; //找到根節點 XmlElement xe = doc.CreateElement("myxml2"); //在根節點下創建元素,如果是屬性,則用XmlAttribute; xe.InnerText = "薪薪代碼hahaha"; //給子節點寫入文本節點(值) xn.AppendChild(xe); //根節點將其納入 doc.Save("new2.xml"); //利用XmlDocument保存文件 }
注意點:在新建根節點的時候,WriteStartElement,只能嵌套,也就是只能有一個根節點。
應用到數據庫,將數據庫的DataSet對象里的值來生成XML文件的元素;
using (SqlConnection con = new SqlConnection("Server=.;DataBase=HGSTUDY;uid=sa;pwd=yao")) { con.Open(); SqlCommand command = new SqlCommand("select * from GL_STUDY", con); command.CommandType = CommandType.Text; DataSet ds = new DataSet("DATASET"); //DATASET將成為XML文件中的根節點名稱,否則系統將其命名為NewDataSet SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = command; sda.Fill(ds, "DATATABLE"); //DATATABLE為所生成XML文件中的子節點名稱,否則系統將其命名為Table。 ds.WriteXml("dbxml.xml"); // DataSet的方法WriteXml將數據寫入到XML文件,就是這么一句話。如果不保存到文件,直接ds.GetXML() }
用一個字符串作為一個XML文檔中的xmlAttribute或xmlElement。[其元素或屬性由類的定義來設置(xml串行化)]
using System;System.xml.Serialization;
先初始化一個類,設置屬性值
var xmlDoc = new XmlDocument(); //Create the xml declaration first xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null)); //Create the root node and append into doc var el = xmlDoc.CreateElement("Contacts"); xmlDoc.AppendChild(el); // Contact XmlElement elementContact = xmlDoc.CreateElement("Contact"); XmlAttribute attrID = xmlDoc.CreateAttribute("id"); attrID.Value = "01"; elementContact.Attributes.Append(attrID); el.AppendChild(elementContact); // Contact Name XmlElement elementName = xmlDoc.CreateElement("Name"); elementName.InnerText = "Daisy Abbey"; elementContact.AppendChild(elementName); // Contact Gender XmlElement elementGender = xmlDoc.CreateElement("Gender"); elementGender.InnerText = "female"; elementContact.AppendChild(elementGender); xmlDoc.Save("test1.xml");
建XmlSerializer實例
class XXX { XmlSerializer ser = new XmlSerializer(Type.GetType("forxml.truck")); Truck tr = new Truck(); tr.ID = 1; tr.cheID = "贛A T34923"; }
Serialize方法–完成對類的串行化
XmlTextWriter xtw = new XmlTextWriter("myxml.xml",Encoding.UTF8); 用XmlTextWriter 創建一個XML文件 ser.Serialize(xtw, tr); //如果只想顯示,可以直接ser.Serialize(Console.Out, tr); }
xml常用方法:
定義xml文檔:XmlDocument xmlDoc = new XmlDocument();
初始化xml文檔:xmlDoc.Load(“D:\book.xml”);//找到xml文件
創建根元素:XmlElement xmlElement = xmlDoc.CreateElement(“”, “Employees”, “”);
創建節點:XmlElement xeSub1 = xmlDoc.CreateElement(“title”);
查找Employees節點:XmlNode root = xmlDoc.SelectSingleNode(“Employees”);
添加節點:xe1.AppendChild(xeSub1);
更改節點的屬性:xe.SetAttribute(“Name”, “李明明”);
移除xe的ID屬性:xe.RemoveAttribute(“ID”);
刪除節點title:xe.RemoveChild(xe2);
public void CreateXMLDocument() { XmlDocument xmlDoc = new XmlDocument(); //加入XML的聲明段落,<?xml version="1.0" encoding="gb2312"?> XmlDeclaration xmlDeclar; xmlDeclar = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null); xmlDoc.AppendChild(xmlDeclar); //加入Employees根元素 XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", ""); xmlDoc.AppendChild(xmlElement); //添加節點 XmlNode root = xmlDoc.SelectSingleNode("Employees"); XmlElement xe1 = xmlDoc.CreateElement("Node"); xe1.SetAttribute("Name", "薪薪代碼"); xe1.SetAttribute("ISB", "2-3631-4"); //添加子節點 XmlElement xeSub1 = xmlDoc.CreateElement("title"); xeSub1.InnerText = "學習VS"; xe1.AppendChild(xeSub1); XmlElement xeSub2 = xmlDoc.CreateElement("price"); xe1.AppendChild(xeSub2); XmlElement xeSub3 = xmlDoc.CreateElement("weight"); xeSub3.InnerText = "20"; xeSub2.AppendChild(xeSub3); root.AppendChild(xe1); xmlDoc.Save("D:\\book.xml");//保存的路徑 }
生成的xml文件如下:
<?xml version="1.0" encoding="GB2312"?> -<Employees>- <Node ISB="2-3631-4" Name="薪薪代碼"> <title>學習VS</title>- <price> <weight>20</weight> </price> </Node> </Employees>
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("D:\\book.xml");//找到xml文件 XmlNode root = xmlDoc.SelectSingleNode("Employees");//查找Employees節點 XmlElement xe1 = xmlDoc.CreateElement("Node2");//添加Node2節點 xe1.SetAttribute("Name", "張飛"); XmlElement xeSub1 = xmlDoc.CreateElement("title");//定義子節點 xeSub1.InnerText = "心情好"; xe1.AppendChild(xeSub1);//添加節點到Node2 root.AppendChild(xe1);//添加節點到Employees xmlDoc.Save("D:\\book.xml");
結果:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="薪薪代碼"> <title>學習VS</title>- <price> <weight>20</weight> </price> </Node>- <Node2 Name="張三"> <title>心情好</title> </Node2>- <Node2 Name="張三"> <title>心情好</title> </Node2> </Employees>
public void ModifyNode() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("D:\\book.xml"); XmlNodeList nodeList = xmlDocument.SelectSingleNode("Employees").ChildNodes;//獲取Employees節點的所有子節點 foreach (XmlNode xn in nodeList)//遍歷 { XmlElement xe = (XmlElement)xn; if (xe.GetAttribute("Name") == "薪薪代碼") { xe.SetAttribute("Name", "薪薪");//更改節點的屬性 XmlNodeList xnl = xe.ChildNodes;//獲取xe的所有子節點 foreach (XmlNode xn1 in xnl) { XmlElement xe2 = (XmlElement)xn1;//將節點xn1的屬性轉換為XmlElement if (xe2.Name == "title")//找到節點名字為title的節點 { xe2.InnerText = "今天天氣不好"; } if (xe2.Name == "price") { XmlNodeList xnl2 = xe2.ChildNodes; foreach (XmlNode xn2 in xnl2) { if (xn2.Name == "weight") { xn2.InnerText = "88"; } } } } } } xmlDocument.Save("D:\\book2.xml"); }
運行結果:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="薪薪"> <title>今天天氣不好</title>-<price> <weight>88</weight> </price> </Node> -<Node2 Name="張三"> <title>心情好</title> </Node2></Employees>
public void DeleteNode() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("D:\\book1.xml"); XmlNodeList xnl = xmlDocument.SelectSingleNode("Employees").ChildNodes; foreach (XmlNode xn in xnl) { if (xn.Name == "Node") { XmlElement xe = (XmlElement)xn;//將xn的屬性轉換為XmlElement xe.RemoveAttribute("ID");//移除xe的ID屬性 XmlNodeList xnl2 = xe.ChildNodes; for (int i = 0; i < xnl2.Count; i++) { XmlElement xe2 = (XmlElement)xnl2.Item(i); if (xe2.Name == "title") { xe.RemoveChild(xe2);//刪除節點title } } } } xmlDocument.Save("D:\\book3.xml"); }
結果:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="薪薪">-<price> <weight>20</weight> </price> </Node>- <Node2 Name="張三"> <title>心情好</title> </Node2>- <Node2 Name="張三"> <title>心情好</title> </Node2> </Employees>
xml文件如下:
<?xml version="1.0" encoding="utf-8" ?> <configurationN> <ServerAddress>1143</ServerAddress> <ID>192.168</ID> </configurationN>
在寫入xml文件時,最主要使用了兩個方法:Load和Save。
Load:初始化xml文檔,以便項目文件獲取具體的xml節點的值。
public void Load(string path) { try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if (xn.Name == configuration_ServerAddress) { ServerAddress = xn.InnerText; } } } catch(Exception ex) { } }
Save:在項目系統中進行修改配置文件值后,需要對xml進行重新保存
public void Save(string path) { try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if (xn.Name == configuration_ServerAddress) { xn.InnerText = ServerAddress; } } xmlDocument.Save(path); } catch (Exception ex) { } }
此處將所有代碼都貼出來,方便下次實現。因為項目是WPF文件,而且都是簡單控件,所以只貼出后臺代碼。
class ConfigurationManager:INotifyPropertyChanged { public const string managerNode = "configurationN";//根節點 public const string configuration_ServerAddress = "ServerAddress";//子節點 private string _ServerAddress; public string ServerAddress { get { return _ServerAddress; } set { _ServerAddress = value; NotifyPropertyChanged("ServerAddress"); } } public void Load(string path) { try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if (xn.Name == configuration_ServerAddress) { ServerAddress = xn.InnerText; } } } catch(Exception ex) { } } public void Save(string path) { try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if (xn.Name == configuration_ServerAddress) { xn.InnerText = ServerAddress; } } xmlDocument.Save(path); } catch (Exception ex) { } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public static ConfigurationManager Instance = new ConfigurationManager(); } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Start(); this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString(); } private string path = "CONFIG\\System.xml"; private void button1_Click(object sender, RoutedEventArgs e) { ConfigurationManager.Instance.ServerAddress = this.tb1.Text; ConfigurationManager.Instance.Save(path); } private void button2_Click(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } private void Start() { ConfigurationManager.Instance.Load(path); } }
以上就是關于“C#讀寫xml文件的方法是什么”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。