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 Code

XML实现用户登录

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增加class
            XmlAttribute 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/p/2618782.html