C# 各种操作xml 简单介绍

   直接上代码大家一看就明白了...


                // xml容器有xmldocuent ,xdocument .xpathdocument///
                /////// xml 加载文件方式分为三种 一,直接xmldoc.load(path) 二.xmldoc.loadxml(string text),三.xmldoc.load(stream strem)///////
                //用linq 加载操作xml///
                var doc1 = XDocument.Load(Server.MapPath("Test.xml"));
                string path = Server.MapPath("Test.xml");
                Readstreamxml(path);
                ReadXml(path);
                string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
                // linq 加载方式 //
                var doc2 = XDocument.Parse(str);
                ///xmldco 加载方式//
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(str);
                //xpathdocument 是只读容器///
                XPathDocument document = new XPathDocument(path);
                XPathNavigator navigator = document.CreateNavigator();
                XPathNodeIterator nodes = navigator.Select("/Customers/Customer");
                while (nodes.MoveNext())
                {
                    Console.WriteLine(nodes.Current.Name);
                }
                //xmldocument xpath 查询//
                XmlNodeList nodelist = xmldoc.SelectNodes("/Customers/Customer");

                //linq xpath 查询//
                var result = from customer in doc1.Descendants("Customer")
                             select customer.Value;
                foreach (var s in result)
                {
                    Console.WriteLine(s);
                }
                var results = (from order in doc1.Descendants("Order")
                               where order.Attribute("OrderID").Value == "1003"
                               select new
                               {
                                   CustomerID = order.Parent.Attribute("id").Value,
                                   Freight = (decimal)order.Attribute("Freight")
                               }).FirstOrDefault();
                Console.WriteLine(string.Format("Customer ID: {0} Freight: {1}", results.CustomerID, results.Freight));

/// <summary>
        /// 以文件 流的方式读取
        /// </summary>
        /// <param name="path"></param>
        private void Readstreamxml(string path)
        {
            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(file);
                XmlNode root = xmldoc.SelectSingleNode("Customers");
                XmlElement xe1 = xmldoc.CreateElement("c");
                root.AppendChild(xe1);
                file.SetLength(0);//将文件指针移到起始位置
                xmldoc.Save(file);

            }

        }

        //以xmlreader 方式读出xml//

        public void ReaderXml(string path)
        {
            XmlReaderSettings xmlsetting = new XmlReaderSettings();
            xmlsetting.ProhibitDtd = false;
            StringBuilder str = new StringBuilder();
            XmlReader xmlreader = XmlReader.Create(path, xmlsetting);
            while (xmlreader.Read())
            {
                switch (xmlreader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xmlreader.IsEmptyElement)
                        {
                            str.Append(string.Format("name:{0}", xmlreader.Name));
                        }
                        else
                        {
                            str.Append(xmlreader.Name);
                            if (xmlreader.HasAttributes)
                            {

                                while (xmlreader.MoveToNextAttribute())
                                {
                                    str.AppendFormat("{0}={1}", xmlreader.Name, xmlreader.Value);
                                }
                            }

                        }
                        break;
                    //后面还有一结点类型//
                }

            }

        }
        /// <summary>
        /// 以textreader方式读取
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string ReadXml(string path)
        {

            //string xmlFile = Server.MapPath(path);

            XmlTextReader reader = new XmlTextReader(path);

            StringBuilder str = new StringBuilder();



            while (reader.Read())
            {

                switch (reader.NodeType)
                {

                    case XmlNodeType.Element:

                        str.Append("Element: <b>").Append(reader.Name).Append("</b><br />");

                        break;

                    case XmlNodeType.Text:

                        str.Append(" - Value: <b>").Append(reader.Value).Append("</b><br />");

                        break;

                    case XmlNodeType.XmlDeclaration:

                        str.Append("Xml Declaration: <b>");

                        str.Append(reader.Name).Append(" ").Append(reader.Value).Append("</b><br />");

                        break;

                }



                if (reader.AttributeCount > 0)
                {

                    while (reader.MoveToNextAttribute())
                    {

                        str.Append(" - Attribute: <b>").Append(reader.Name);

                        str.Append("</b> Value: <b>").Append(reader.Value).Append("</b><br />");

                    }

                }

            }

            reader.Close();

            return str.ToString();

        }

原文地址:https://www.cnblogs.com/cxlings/p/2784405.html