標籤:des style blog http io color ar os 使用
person.xml
<?xml version="1.0" encoding="utf-8"?><MyP> <P1> <Person id="cz001"> <Name>張三</Name> <Age>18</Age> </Person> <Person id="cz002"> <Name>李四</Name> <Age>19</Age> </Person> <Person id="cz003"> <Name>王五</Name> <Age>20</Age> </Person> </P1> <P2> <Person> <Name>張三2</Name> <Age>18</Age> </Person> <Person> <Name>李四2</Name> <Age>19</Age> </Person> <Person> <Name>王五2</Name> <Age>20</Age> </Person> </P2></MyP>
View Code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace Xml操作{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //讀取XML System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("person.xml"); System.Xml.Linq.XElement xeRoot = xdoc.Root; //根節點 System.Xml.Linq.XElement xele = xeRoot.Element("P1").Element("Person"); //子節點 MessageBox.Show("id=" + xele.Attribute("id").Value); //cz001 foreach (var ele in xele.Elements()) { string str = string.Format("Name={0},Value={1}", ele.Name.ToString(), ele.Value); MessageBox.Show(str); } } private void Form1_Load(object sender, EventArgs e) { //*讀取XML資料載入到treeView1列表中。 //1、載入person.xml System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("person.xml"); //2、擷取根節點,MyP System.Xml.Linq.XElement xeRoot = xdoc.Root; //3、先把根節點添加到treeView1上 TreeNode treeViewRoot = treeView1.Nodes.Add(xeRoot.Name.LocalName); //4、開始遍曆所有的子節點,使用遞迴 LoadTreeNodes(xeRoot, treeViewRoot); //*寫入XML檔案。 //1、建立XML對象 System.Xml.Linq.XDocument xdocument = new System.Xml.Linq.XDocument(); //2、建立跟節點 System.Xml.Linq.XElement eRoot = new System.Xml.Linq.XElement("根節點"); //添加到xdoc中 xdocument.Add(eRoot); //3、添加子節點 System.Xml.Linq.XElement ele1 = new System.Xml.Linq.XElement("子節點1"); ele1.Value = "內容1"; eRoot.Add(ele1); //4、為ele1節點添加屬性 System.Xml.Linq.XAttribute attr = new System.Xml.Linq.XAttribute("url", "http://www.baidu.com"); ele1.Add(attr); //5、快速添加子節點方法 eRoot.SetElementValue("子節點2", "內容2"); //6、快速添加屬性 ele1.SetAttributeValue("id", 12); //7、最後儲存到檔案,也可以寫入到流中。 xdocument.Save("123.xml"); } private void LoadTreeNodes(System.Xml.Linq.XElement xeRoot, TreeNode treeViewRoot) { //把xeRoot下面的所有內容迴圈綁定treeView上 foreach (System.Xml.Linq.XElement ele in xeRoot.Elements()) { //判定子根節點下是否還有子節點 if (ele.Elements().Count() > 0) { TreeNode node = treeViewRoot.Nodes.Add(ele.Name.ToString()); //寫入Name值 //擷取節點上的屬性方法 System.Xml.Linq.XAttribute attr = ele.Attribute("id"); if (attr != null) { node.Text += string.Format(" [{0}={1}]", attr.Name, attr.Value); } LoadTreeNodes(ele, node); //遍曆迴圈 } else { treeViewRoot.Nodes.Add(ele.Value); //寫入節點下的Value } } } }}
C# Xml Linq XDocument 基本操作