寫入xml文件
第一種方法:使用XmlDocument類:
Demo1
//通過代碼創建XML文檔
//1、引用命名空間 System.Xml //2、創建一個 xml 文檔 XmlDocument xml = new XmlDocument(); //3、創建一行聲明信息,並添加到 xml 文檔頂部 XmlDeclaration decl = xml.CreateXmlDeclaration("1.0", "utf-8", null); xml.AppendChild(decl); //4、創建根節點 XmlElement rootEle = xml.CreateElement("人"); xml.AppendChild(rootEle); //5、創建子結點|屬性:性別 XmlElement childEle = xml.CreateElement("性別"); rootEle.AppendChild(childEle); XmlElement c2Ele = xml.CreateElement("男"); c2Ele.InnerText = "1"; childEle.AppendChild(c2Ele); c2Ele = xml.CreateElement("女"); c2Ele.InnerText = "0"; childEle.AppendChild(c2Ele); //6、創建子節點|屬性:四肢 childEle = xml.CreateElement("胳膊"); rootEle.AppendChild(childEle); c2Ele = xml.CreateElement("右胳膊"); c2Ele.InnerText = "一般"; childEle.AppendChild(c2Ele); c2Ele = xml.CreateElement("左胳膊"); c2Ele.InnerText = "一般"; childEle.AppendChild(c2Ele); c2Ele = xml.CreateElement("左退"); c2Ele.InnerText = "粗壯"; childEle.AppendChild(c2Ele); c2Ele = xml.CreateElement("右腿"); c2Ele.InnerText = "粗壯"; childEle.AppendChild(c2Ele); xml.Save(@"C:\Users\Administrator\Desktop\Test\test.xml");
-----------------------------------------------------------------------------------------------
Demo2
try
{
//初始化一個xml實例 XmlDocument myXmlDoc = new XmlDocument(); //創建xml的根節點 XmlElement rootElement = myXmlDoc.CreateElement("Computers"); //將根節點加入到xml文件中(AppendChild) myXmlDoc.AppendChild(rootElement); //初始化第一層的第一個子節點 XmlElement firstLevelElement1 = myXmlDoc.CreateElement("Computer"); //填充第一層的第一個子節點的屬性值(SetAttribute) firstLevelElement1.SetAttribute("ID", "11111111"); firstLevelElement1.SetAttribute("Description", "Made in China"); //將第一層的第一個子節點加入到根節點下 rootElement.AppendChild(firstLevelElement1); //初始化第二層的第一個子節點 XmlElement secondLevelElement11 = myXmlDoc.CreateElement("name"); //填充第二層的第一個子節點的值(InnerText) secondLevelElement11.InnerText = "Lenovo"; firstLevelElement1.AppendChild(secondLevelElement11); XmlElement secondLevelElement12 = myXmlDoc.CreateElement("price"); secondLevelElement12.InnerText = "5000"; firstLevelElement1.AppendChild(secondLevelElement12); XmlElement firstLevelElement2 = myXmlDoc.CreateElement("Computer"); firstLevelElement2.SetAttribute("ID", "2222222"); firstLevelElement2.SetAttribute("Description", "Made in USA"); rootElement.AppendChild(firstLevelElement2); XmlElement secondLevelElement21 = myXmlDoc.CreateElement("name"); secondLevelElement21.InnerText = "IBM"; firstLevelElement2.AppendChild(secondLevelElement21); XmlElement secondLevelElement22 = myXmlDoc.CreateElement("price"); secondLevelElement22.InnerText = "10000"; firstLevelElement2.AppendChild(secondLevelElement22); //將xml文件保存到指定的路徑下 myXmlDoc.Save(@"C:\Users\Administrator\Desktop\Test\test.xml"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
第二種方法:使用XmlTextWriter類:
//XmlTextWriter寫文件的時候, 默認是覆蓋以前的文件, 如果此文件名不存在,它將創建此文件.首先設置一下,你要創建的XML文件格式,
//然后可以通過WriteStartElement和WriteElementString方法來創建元素,這兩者的區別就是如果有子結點的元素,那么創建的時候就用WriteStartElement,然后去創建子元素,創建完畢后,要調用相應的WriteEndElement來告訴編譯器,創建完畢,用WriteElementString來創建單個的元素,用WriteAttributeString來創建屬性.如下: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"C:\Users\Administrator\Desktop\Test\test.xml", null); //使用 Formatting 屬性指定希望將 XML 設定為何種格式。 這樣,子元素就可以通過使用 Indentation 和 IndentChar 屬性來縮進。 myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartDocument(false); myXmlTextWriter.WriteStartElement("日期"); myXmlTextWriter.WriteComment("這是廚房的下單記錄"); myXmlTextWriter.WriteStartElement("申購單"); myXmlTextWriter.WriteAttributeString("部門", "中廚房"); myXmlTextWriter.WriteAttributeString("申購人", "趙亮"); for (int i = 0; i < 10; i++) { myXmlTextWriter.WriteElementString("編號", "0001"); myXmlTextWriter.WriteElementString("編碼", "gcxg"); myXmlTextWriter.WriteElementString("名稱", "國產西瓜"); myXmlTextWriter.WriteElementString("規格", "4只/每箱"); myXmlTextWriter.WriteElementString("單價", "88.5"); myXmlTextWriter.WriteElementString("單位", "箱"); myXmlTextWriter.WriteElementString("數量", "5"); myXmlTextWriter.WriteElementString("金額", "450"); myXmlTextWriter.WriteElementString("備注", "要熟的"); } myXmlTextWriter.Flush(); myXmlTextWriter.Close();
第三種方法:使用LINQ to XML 的XDocument類:
var doc = new XDocument(new XElement("Contacts", new XElement("Contact", new XAttribute("id", "01"), new XElement("Index", "0001"), new XElement("Code", "gcxg"), new XElement("Name", "國產西瓜"), new XElement("spec", "4只/每箱"), new XElement("Price", "80"), new XElement("Unit", "箱"), new XElement("Number", "4"), new XElement("Total", "320"), new XElement("Remakes", "要熟的") ))); doc.Save(@"C:\Users\Administrator\Desktop\Test\test.xml");
=====================================================================================================
讀寫完整示例
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Linq; namespace _45_Xml讀寫 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 創建節點 /// </summary> /// <param name="xmldoc"></param> xml文檔 /// <param name="parentnode"></param>父節點 /// <param name="name"></param> 節點名 /// <param name="value"></param> 節點值 /// public static void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) { XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); } private void WriteXml_Click(object sender, EventArgs e) { //創建一個 xml 文檔 XmlDocument xmlDoc = new XmlDocument(); //創建類型聲明節點 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""); xmlDoc.AppendChild(node); //創建根節點 XmlElement noteRoot = xmlDoc.CreateElement("R"); //給節點屬性賦值 noteRoot.SetAttribute("version", "1.0"); noteRoot.SetAttribute("Title", "Demo"); xmlDoc.AppendChild(noteRoot); for (int i = 0; i < 4; i++) { XmlElement RootClass1 = xmlDoc.CreateElement("A"); XmlNode NoteClass1 = xmlDoc.SelectSingleNode("R"); if (NoteClass1 != null) NoteClass1.AppendChild(RootClass1); CreateNode(xmlDoc, RootClass1, "A-value", "avalue");//可以復制多條 XmlElement RootClass2 = xmlDoc.CreateElement("B"); XmlNode NoteClass2= xmlDoc.SelectSingleNode("R").SelectNodes("A").Item(i); if (NoteClass2 != null) NoteClass2.AppendChild(RootClass2); CreateNode(xmlDoc, RootClass2, "B-value", "bvalue");//可以復制多條 XmlElement RootClass3 = xmlDoc.CreateElement("C");//添加子節點 XmlNode NoteClass3 = xmlDoc.SelectSingleNode("R").SelectNodes("A").Item(i).SelectSingleNode("B"); if (NoteClass3 != null)NoteClass3.AppendChild(RootClass3); CreateNode(xmlDoc, RootClass3, "C-value", "cvalue");//可以復制多條 } xmlDoc.Save(@"C:\Users\Administrator\Desktop\Test\test.xml"); } private void ReadXml_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; //忽略文檔里面的注釋 XmlReader reader = XmlReader.Create(@"C:\Users\Administrator\Desktop\Test\test.xml", settings); xmlDoc.Load(reader); //然后可以通過調用SelectSingleNode得到指定的結點,通過GetAttribute得到具體的屬性值.參看下面的代碼 // 得到根節點bookstore XmlNode mainNote = xmlDoc.SelectSingleNode("R"); //通過 日期 根節點來讀取XML文件 if (mainNote != null) //如果根節點存在 { XmlNodeList childNote = mainNote.ChildNodes; //聲明一個獲取所有子節點的集合 foreach (XmlNode outchildNote in childNote) //在這個集合中遍歷所有子節點 { XmlElement bookNote = (XmlElement) outchildNote; // 將節點轉換為元素,便於得到節點的屬性值 XmlNodeList singleNote = bookNote.ChildNodes; // 將所有節點屬性(也就是最終的值)放進節點集合 foreach (XmlNode outNote in singleNote) //遍歷節點屬性 { listBox1.Items.Add(outNote.InnerText); } // listBox1.Items.Add(bookNote.GetAttribute("部門").ToString()); // 得到Type和ISBN兩個屬性的屬性值 // listBox1.Items.Add(bookNote.GetAttribute("申購人").ToString()); } } } } }
