首页 > 代码库 > C#操作XML文档总结
C#操作XML文档总结
包括XMLWriter写入,XmlReader读取,XmlDocument操作,DataSet.ReadXML(),DataSet.WriteXML(),LINQ查询XML
1.XMLWriter写入XML数据
结果会覆盖原文档。
c#_code:
//使用XMLWriter写XML数据 XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; //缩进 //settings.NewLineOnAttributes = true; //属性换新的一行 XmlWriter writer = XmlWriter.Create("Books.xml", settings);//创建XmlWriter实例 writer.WriteStartDocument();//XML文档声明 writer.WriteStartElement("book"); //开始标记 1 writer.WriteAttributeString("Type","科幻");//添加属性 writer.WriteAttributeString("ISBN", "001-001-001");//添加属性 writer.WriteElementString("title", "名侦探柯南");//添加元素 writer.WriteElementString("price", "99.99");//添加元素 writer.WriteStartElement("author");//开始标记 2 writer.WriteElementString("name", "谁谁谁");//添加元素 writer.WriteEndElement();//结束标记 2 writer.WriteEndElement();//结束标记 1 writer.WriteEndDocument(); //关闭所有文档标记 writer.Flush(); //刷新流 writer.Close(); //关闭流
结果如下:
<?xml version="1.0" encoding="utf-8"?><book Type="科幻" ISBN="001-001-001"> <title>名侦探柯南</title> <price>99.99</price> <author> <name>谁谁谁</name> </author></book>
2.XMLReader读取XML数据
xml_data:
<?xml version="1.0" encoding="utf-8"?><book Type="科幻" ISBN="001-001-001"> <title>哈利波特</title> <price>99.99</price> <author> <name>JK罗琳</name> </author></book><book Type="青春" ISBN="001-001-002"> <title>左耳</title> <price>9.99</price> <author> <name>饶雪漫</name> </author></book><book Type="悬疑" ISBN="001-001-003"> <title>盗墓笔记</title> <price>99.99</price> <author> <name>南派三叔</name> </author></book>
c#_code:
此处待续。。。。
3.XmlDocument操作XML
(1)插入节点,在原文档下追加,原文档必须要有根元素 <Books></Books>。
c#_code:
XmlDocument doc = new XmlDocument(); doc.Load("D:\\Books.xml");//加载XML文档,文件必须存在且有根元素 //创建一个节点 XmlElement newbook = doc.CreateElement("book"); //设置属性 newbook.SetAttribute("type", "story"); newbook.SetAttribute("publishdate", "1993"); newbook.SetAttribute("ISBN", "002-123-321"); //设置元素 XmlElement name = doc.CreateElement("Name"); name.InnerText = "I have a Dream"; newbook.AppendChild(name); XmlElement price = doc.CreateElement("Price"); price.InnerText = "9.99"; newbook.AppendChild(price); //添加到节点 doc.DocumentElement.AppendChild(newbook); //写入磁盘(追加) XmlTextWriter tr = new XmlTextWriter("D:\\Books.xml", null); tr.Formatting = Formatting.Indented;//设置缩进格式 doc.WriteContentTo(tr);//保存 写入 tr.Close();
结果如下:
<?xml version="1.0" encoding="utf-8"?><Books> <book type="story" publishdate="1993" ISBN="002-123-321"> <Name>I have a Dream</Name> <Price>9.99</Price> </book></Books>
(2)XmlDocument读取某个节点的元素
xml_data:
<?xml version="1.0" encoding="utf-8"?><bookstore> <book Type="科幻" ISBN="001-001-001"> <title>哈利波特</title> <price>99.99</price> <author> <name>JK罗琳</name> </author> </book> <book Type="青春" ISBN="001-001-002"> <title>左耳</title> <price>9.99</price> <author> <name>饶雪漫</name> </author> </book> <book Type="悬疑" ISBN="001-001-003"> <title>盗墓笔记</title> <price>99.99</price> <author> <name>南派三叔</name> </author> </book></bookstore>
c#_code:
XmlDocument doc = new XmlDocument(); doc.Load("D:\\Books.xml"); //输出所有节点为Name的元素 //1. XmlNodeList nodelist = doc.GetElementsByTagName("title"); //2.使用XPath语法从文档中检索一组节点 //XmlNodeList nodelist = doc.SelectNodes("/bookstore/book/title"); foreach (XmlNode node in nodelist) { richTextBox1.AppendText(node.InnerXml + "\r\n"); }
读取结果:
哈利波特
左耳
盗墓笔记
(2)XMLDocument获取指定节点的元素
4.XML文档与ADO.NET对象相互转换
适用于版本.NET3.0以上
using System.Data; using System.Xml; using System.Data.SqlClient; using System.Xml.Linq; string connString = "server=服务器名;database=数据库;uid=账户;pwd=密码"; ///ADO.NET数据转换XML文档 //1:创建一个ADO.NET对象,生成一个DataSet对象 SqlConnection conn = new SqlConnection(connString); SqlDataAdapter dataAdapter1 = new SqlDataAdapter("select Barcode from Books", conn); DataSet dataSet1 = new DataSet(); dataAdapter1.Fill(dataSet1, "BooksBarCode"); //2:把XML文档存到磁盘中(覆盖数据) string file = @"C:\Users\WIN20150720\Desktop\Books.xml"; dataSet1.WriteXml(file); ///XML文档转换ADO.NET数据 //1:创建DataSet对象 DataSet dataSet2 = new DataSet(); //2:读取XML文档 dataSet2.ReadXml(file); //3:绑定到网格 dataGridView1.DataSource = dataSet2.Tables[0]; ///SQL从数据库查询 //根据BarCode获取全部信息 string barcode = ""; foreach (DataRow dr in dataSet2.Tables[0].Rows) { barcode += dr["Barcode"].ToString() + ","; } barcode = barcode.Substring(0, barcode.LastIndexOf(",")); string sql = string.Format("Select * from Books where BarCode in({0})", barcode); SqlDataAdapter dataAdapter2 = new SqlDataAdapter(sql, conn); DataSet dataSet3 = new DataSet(); dataAdapter2.Fill(dataSet3, "BooksInfo"); string file2 = @"C:\Users\WIN20150720\Desktop\AllBooks.xml"; dataSet3.WriteXml(file2);
5.LINQ从XML文档查询
(1)
data_xml:
<?xml version="1.0" encoding="utf-8" ?><Data> <Products> <Product Name="West Side Story" Price="9.99m" SuppelierID="1"/> <Product Name="Assassins" Price="14.99m" SuppelierID="2"/> <Product Name="Frogs" Price="13.99m" SuppelierID="1"/> <Product Name="Sweeney Todd" Price="9.99m" SuppelierID="3"/> </Products> <Suppliers> <Supplier Name="Solely Sondheim" SupplierID="1"/> <Supplier Name="CD-by-CD-by-Sondheim" SupplierID="2"/> <Supplier Name="Barbershop CDs" SupplierID="3"/> </Suppliers></Data>
应用:
using System.Xml.Linq;namespace ConsoleApplication1{ class XML_LINQ { static void Main() { //将产品和供货商连接起来,价格高于10美元,先按供货商名排序,在按产品名排序,最后打印供货商名和产品名 //供货商和产品编码使用XML文件 XDocument doc = XDocument.Load("data.xml"); //XDocument使用命名空间System.Xml.Linq; var filtered = from p in doc.Descendants("Product") join s in doc.Descendants("Supplier") on (int)p.Attribute("SupplierID") equals (int)s.Attribute("SupplierID") where (decimal)p.Attribute("Price") > 10 orderby (string)s.Attribute("Name"), (string)p.Attribute("Name") select new { SupplierName = (string)s.Attribute("Name"), ProductName = (string)s.Attribute("Name") }; foreach (var v in filtered) { Console.WriteLine("Supplier={0};Product={1}", v.SupplierName, v.ProductName); } } }}
(2)
xml_data: D:\\Books.xml
<?xml version="1.0" encoding="utf-8"?><bookstore> <book Type="科幻" ISBN="001-001-001"> <title>哈利波特</title> <price>99.99</price> <author> <name>JK罗琳</name> </author> </book> <book Type="青春" ISBN="001-001-002"> <title>左耳</title> <price>9.99</price> <author> <name>饶雪漫</name> </author> </book> <book Type="悬疑" ISBN="001-001-003"> <title>盗墓笔记</title> <price>99.99</price> <author> <name>南派三叔</name> </author> </book></bookstore>
应用1:根据书名查找价格和作者
//根据书名查找价格和作者
XDocument doc = XDocument.Load("D:\\Books.xml"); var query = from p in doc.Element("bookstore").Elements("book") where (string)p.Element("title") == "左耳" select p; query.ToList().ForEach(item => { decimal price = (decimal)item.Element("price"); string author = item.Element("author").Value; });
结果:price=9.99 author=饶雪漫
应用2:查找所有的书名
//查找所有的书名 XDocument xdoc = XDocument.Load("D:\\Books.xml"); var query = from title in xdoc.Descendants("title") select title.Value; foreach (var item in query) { richTextBox1.AppendText(item + "\r\n"); }
结果: 哈利波特
左耳
盗墓笔记
C#操作XML文档总结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。