C# XML
XML文檔對象模型
XML文檔對象模型(Document Object Model,DOM是一組以非常直觀的方式訪問和處理XML的類。構成DOM的類在命名空間System.Xml中。
XmlNode 表示文檔中一個節點
XmlDocument表示 XML 文檔。
XmlElement 表示Xml文檔中一個元素。
XmlAttribute 表示一個特性
XmlText 表示開始標記和結束標記之間的文本
XmlNodeList 表示一個節點集合
XmlNodeReader
string xmlPath = @"bookstore.xml";XmlDocument doc = new XmlDocument();doc.Load(xmlPath);//指定要獲取節點的路徑XmlNode bookNode = doc.SelectSingleNode("/bookstore/book");XmlNodeReader reader = new XmlNodeReader(bookNode);while (reader.Read()){//顯示節點的名稱和值if (reader.NodeType == XmlNodeType.Element){listBox1.Items.Add("Node Name:" + reader.Name);}if (reader.NodeType == XmlNodeType.Text){listBox1.Items.Add("Node Value:" + reader.Value);}}?
讀取某一子節點屬性:
System.Xml.XmlDocument doc = new XmlDocument();doc.LoadXml("<Students><Student><Name>XiaoYue</Name><Age>19</Age><Sex>女</Sex></Student>" +"<Student><Name nick=\"阿柯\">TingPoen</Name><Age>23</Age><Sex>男</Sex></Student>" +"</Students>");string nickName = doc.ChildNodes[0].ChildNodes[1].ChildNodes[0].Attributes["nick"].Value;MessageBox.Show(nickName);讀取某一節點文本:
string nickname, loginname;XmlDocument xDoc = new XmlDocument();xDoc.Load("login_info.xml");XmlNode xnUserInfo = xDoc.DocumentElement.SelectSingleNode("user_info");nickname = xnUserInfo.ChildNodes[1].InnerText;loginname = xnUserInfo.ChildNodes[2].InnerText;刪除節點
View CodeXML實現用戶登錄
XML <LoginList><user><Username>admin</Username><Password>123456</Password></user><user><Username>root</Username><Password>112233456</Password></user><user><Username>zht</Username><Password>Zht!@#</Password></user> </LoginList> View Code string username = textBox1.Text;string userpwd = textBox2.Text;XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("LoginList.xml");XmlNodeList usersList = xmlDoc.SelectNodes("/LoginList/user");bool isLogin = false;for (int i = 0; i < usersList.Count; i++){if (username.Equals(usersList[i].SelectSingleNode("Username").InnerText) && (userpwd.Equals(usersList[i].SelectSingleNode("Password").InnerText))){isLogin = true;break;}}if (isLogin == true){//轉到你要的界面MessageBox.Show("登錄成功");}else{//轉到錯誤頁面MessageBox.Show("登錄失敗");}XmlReader類?表示提供對 XML 數據進行快速、非緩存、只進訪問的讀取器。
http://msdn.microsoft.com/zh-cn/library/system.xml.xmlreader.aspx
View Code XmlReader reader = XmlReader.Create(filename);while (reader.Read()){if (reader.NodeType == XmlNodeType.Element){switch (reader.Name){case "pa_nd":NianduStr = reader.ReadString();break;case "pa_xz":XiuzhengStr = reader.ReadString();break;case "pa_zf":ZhengfuStr = reader.ReadString();cmbZhengfuTemp = transcmbZhengfuInt(ZhengfuStr);break;case "pa_jr":JiaoduStr = reader.ReadString();break;case "pa_tan":JiaoduTanStr = reader.ReadString();break;case "pa_zq":ZhouqiStr = reader.ReadString();break;case "pa_per":PersentStr = reader.ReadString();break;case "pa_jq":ModelStr = reader.ReadString();cmbModelTemp = transcmbModelInt(ModelStr);break;case "pa_cw":ChaoweiStr = reader.ReadString();break;case "pa_qs":QishiStr = reader.ReadString();break;case "pa_zz":ZhongzhiStr = reader.ReadString();break;case "pa_cf":ChengxingJiaoduStr = reader.ReadString();break;case "pa_sb":ChengxingShoubianStr = reader.ReadString();break;case "pa_a1":Para1Str = reader.ReadString();break;case "pa_av1":Para1ValueStr = reader.ReadString();break;case "pa_a2":Para2Str = reader.ReadString();break;case "pa_av2":Para2ValueStr = reader.ReadString();break;case "pa_a3":Para3Str = reader.ReadString();break;case "pa_av3":Para3ValueStr = reader.ReadString();break;case "pa_a4":Para4Str = reader.ReadString();break;case "pa_av4":Para4ValueStr = reader.ReadString();break;case "pa_a5":Para5Str = reader.ReadString();break;case "pa_av5":Para5ValueStr = reader.ReadString();break;case "pa_a6":Para6Str = reader.ReadString();break;case "pa_av6":Para6ValueStr = reader.ReadString();break;case "pa_a7":Para7Str = reader.ReadString();break;case "pa_av7":Para7ValueStr = reader.ReadString();break;case "pa_a8":Para8Str = reader.ReadString();break;case "pa_av8":Para8ValueStr = reader.ReadString();break;case "pa_a9":Para9Str = reader.ReadString();break;case "pa_av9":Para9ValueStr = reader.ReadString();break;case "pa_a10":Para10Str = reader.ReadString();break;case "pa_av10":Para10ValueStr = reader.ReadString();break;default:break;}}}XmlWriter類?表示一個編寫器,該編寫器提供一種快速、非緩存和只進的方式來生成包含 XML 數據的流或文件。
View Code //XmlTextWriter xmlTw = new XmlTextWriter("xmlFile.xml", System.Text.Encoding.UTF8);XmlWriter xmlTw = XmlWriter.Create("xmlFile.xml");//添加XML的聲明 xmlTw.WriteStartDocument();//新建Book根節點xmlTw.WriteStartElement("Book");//根節點添加id屬性xmlTw.WriteAttributeString("id", "99");//根節點添加title屬性xmlTw.WriteAttributeString("title", "ASP.NET電子商務網站開發全揭秘");//生成BookInfo節點xmlTw.WriteStartElement("BookInfo");//BookInfo增加onwer屬性xmlTw.WriteAttributeString("onwer", "張林");//BookInfo增加class屬性xmlTw.WriteAttributeString("class", "電子商務");xmlTw.WriteEndElement();xmlTw.WriteStartElement("BookAuthorInfo");xmlTw.WriteAttributeString("Class", "Web");xmlTw.WriteAttributeString("Author", "李偉");xmlTw.WriteEndElement();xmlTw.WriteEndElement();//添加Book根節點結束標記 xmlTw.WriteEndDocument();xmlTw.Flush();//保存XML文檔xmlTw.Close(); View Code System.Xml.XmlDocument doc = new XmlDocument();XmlDeclaration xmldecl;//添加XML的聲明xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);System.Xml.XmlElement root = doc.DocumentElement;doc.InsertBefore(xmldecl, root);//新建Book根節點System.Xml.XmlNode root1 = doc.CreateNode("element", "Book", "");//根節點加到XML中去 doc.AppendChild(root1);//根節點添加id屬性XmlAttribute attrid = doc.CreateAttribute("id");attrid.Value = "99";root1.Attributes.SetNamedItem(attrid);//根節點添加title屬性XmlAttribute attrtitle = doc.CreateAttribute("title");attrtitle.Value = "ASP.NET電子商務網站開發全揭秘";root1.Attributes.SetNamedItem(attrtitle);//生成BookInfo節點System.Xml.XmlNode BookInfo = doc.CreateNode("element", "BookInfo", "");//BookInfo增加onwer屬性XmlAttribute attronwer = doc.CreateAttribute("onwer");attronwer.Value = "張林";BookInfo.Attributes.SetNamedItem(attronwer);//BookInfo增加classXmlAttribute attrclass = doc.CreateAttribute("class");attrclass.Value = "電子商務";BookInfo.Attributes.SetNamedItem(attrclass);//BookInfo節點加到根節點Book的子節點里 root1.AppendChild(BookInfo);System.Xml.XmlNode BookAuthorInfo = doc.CreateNode("element", "BookAuthorInfo", "");XmlAttribute attrClass2 = doc.CreateAttribute("Class");attrClass2.Value = "Web";BookAuthorInfo.Attributes.SetNamedItem(attrClass2);XmlAttribute attrAuthor = doc.CreateAttribute("Author");attrAuthor.Value = "李偉";BookAuthorInfo.Attributes.SetNamedItem(attrAuthor);root1.AppendChild(BookAuthorInfo);//保存XML文檔doc.Save("C:\\Book.xml");XML讀入TreeView
xml <?xml version="1.0" encoding="utf-8"?> <bookstore><book genre="操作系統" ISBN="2-3631-1"><title>精解Windows 7</title><publisher>清華大學出版社</publisher><price>49</price></book><book genre="數據庫" ISBN="2-3631-2"><title>SQL基礎教程(第3版)</title><publisher>人民郵電出版社</publisher><price>69</price></book><book genre="影視動畫" ISBN="2-3631-3"><title>After Effects影視合成與特效火星風暴</title><publisher>電子工業出版社</publisher><price>98</price></book> </bookstore> View Code XmlDocument xml = new XmlDocument();xml.Load("bookstore.xml");XmlNode xmlRoot = xml.ChildNodes[1];//得到XML的根結點,ChildNodes[0]指向<?xml version="1.0" encoding="utf-8"?> for (int i = 0; i < xmlRoot.ChildNodes.Count; i++){XmlNode xmlChd = xmlRoot.ChildNodes[i];if (xmlChd is System.Xml.XmlComment) //如果當前節點是注釋,跳過continue;//添加樹的根結點TreeNode treeRoot = new TreeNode();treeRoot.Text = xmlChd.Attributes["genre"].Value; //設置結點的顯示文字//treeRoot.Expanded = true; //設置結點的初始狀態為展開//treeRoot.SelectAction = TreeNodeSelectAction.Expand;//設置結點的點擊操作為展開或收攏結點 treeView1.Nodes.Add(treeRoot);//添加當前根結點的子結點for (int j = 0; j < xmlChd.ChildNodes.Count; j++){XmlNode xmlLeaf = xmlChd.ChildNodes[j];if (xmlLeaf is System.Xml.XmlComment) //如果當前節點是注釋,跳過continue;TreeNode treeLeaf = new TreeNode();treeLeaf.Text = xmlLeaf.InnerText; //設置結點的顯示文字 treeRoot.Nodes.Add(treeLeaf);}}Xpath
Xpath是XML文檔的查詢語言,就像SQL是關系型數據庫的查詢語言一樣。
SelectSingleNode 選擇一個節點
SelectNodes 以XmlNodesList 類的形式返回一個節點類型
View Code private string Loadxml(string name){XmlDocument xdoc = new XmlDocument(); //創建XmlDocument對象; xdoc.Load("message.xml"); //用虛擬路徑轉換為實際路徑,讀取XML文件。 XmlNode xnode = xdoc.DocumentElement.SelectSingleNode("//message[@msgno='" + name + "']/msg"); //通過XPath查找所需要的結點,關于XPath可以自己搜索相關信息。 return xnode.InnerText; //返回結點的內容。 } View Code string file = @"c:\ipaddress.xml";XmlDataDocument doc = new XmlDataDocument();doc.Load(file);XmlNodeList nodes = doc.SelectNodes("IpAddress/content/ipinfo[@connetaddress='192.168.1.14' and @sport='6000']");foreach (XmlNode node in nodes){node.Attributes["state"].Value = "連接成功";}doc.Save(file);MSXML(Microsoft XML Core Services) 是一種XML語言解析器,用來解析XML語言。 它是基于COM的組件,因此使用MSXML先在項目中添加對MSXML的應用。
View Code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MSXML2; namespace msxmlDemo {public partial class Form1 : Form{private DOMDocument60 doc;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){doc = new DOMDocument60();doc.load(@"famousBook.xml");IXMLDOMNodeList nodes = doc.selectNodes("BookShop/Book");IXMLDOMNode node = nodes.nextNode();while (node != null){IXMLDOMNode nameNode = node.firstChild;string nodeText = nameNode.text;listBox1.Items.Add(nodeText);node = nodes.nextNode();}}private void listBox1_SelectedIndexChanged(object sender, EventArgs e){string strItem = listBox1.SelectedItem.ToString();IXMLDOMNode node = doc.selectSingleNode("BookShop/Book[Name='" + strItem + "']");txtAuthor.Text = node.selectSingleNode("Author").text;txtDate.Text = node.selectSingleNode("Date").text;txtISBN.Text = node.attributes.getNamedItem("ISBN").text;txtMoney.Text = node.selectSingleNode("Money").text;txtName.Text = node.selectSingleNode("Name").text;txtOtherName.Text = node.selectSingleNode("OtherName").text;txtOut.Text = node.selectSingleNode("Out").text;}} }XML序列化
類 public class Person{public Person(){}public Person(string _Name, string _ID){Name = _Name;ID = _ID;}public string Name;public string ID;}[Serializable()][XmlRoot]public class Manifest{private Head _Head;[XmlElement]public Head Head{get { return _Head; }set { _Head = value; }}private Declaration _Declaration;[XmlElement]public Declaration Declaration{get { return _Declaration; }set { _Declaration = value; }}}public class Head{string _MessageID = String.Empty;[XmlElement]public string MessageID{get { return _MessageID; }set { _MessageID = value; }}string _MessageType = String.Empty;[XmlAttribute]public string MessageType{get { return _MessageType; }set { _MessageType = value; }}string _SenderID = String.Empty;[XmlElement]public string SenderID{get { return _SenderID; }set { _SenderID = value; }}string _ReceiverID = String.Empty;[XmlElement]public string ReceiverID{get { return _ReceiverID; }set { _ReceiverID = value; }}}public class Declaration{} View Code private void Form2_Load(object sender, EventArgs e){//Person person1 = new Person("悅桐", "HN372E1156008");//XmlSerializer s = new XmlSerializer(typeof(Person));//TextWriter w = new StreamWriter("person1.xml");//s.Serialize(w, person1);//w.Close(); Manifest f = new Manifest();f.Head = new Head();f.Head.MessageID = "00001";f.Head.MessageType = "Application";f.Head.SenderID = "ZHHT";f.Head.ReceiverID = "Somboy";f.Declaration = new Declaration();XmlSerializer s1 = new XmlSerializer(typeof(Manifest));TextWriter w1 = new StreamWriter("mainfest1.xml");s1.Serialize(w1, f);w1.Close();}DataSet 與 Xml
DataSet生成Xml Current_DS_Grid = DBClass.GetDataSet(DBOperationClass.GY_SQL_Str, "tb_CurrentGongyiPara");string fileName = ceFilePath + "\\" + "CurrentGongyiPara.xml";DirectoryInfo ceDir = new DirectoryInfo(ceFilePath);if (ceDir.Exists){}else{ceDir.Create();}Current_DS_Grid.WriteXml(fileName, XmlWriteMode.WriteSchema); Xml導入DataSet DataSet xmlds = new DataSet();xmlds.ReadXml(ceFilePath + "\\" + XMLfileName);dataGrid1.DataSource = xmlds.Tables[0];注:本文部分代碼來自《C#網絡編程大講堂》!!!
?
復制搜索 復制搜索 復制搜索 復制搜索 復制搜索 復制搜索轉載于:https://www.cnblogs.com/YuanSong/archive/2012/08/01/2618782.html
總結
- 上一篇: datasg中数据的存储结构
- 下一篇: C# 打开word 语法拼写错误太多 解