c#操作xml的完整例子.pdf

上传人:tbuqq 文档编号:5335241 上传时间:2020-04-19 格式:PDF 页数:4 大小:49.65KB
返回 下载 相关 举报
c#操作xml的完整例子.pdf_第1页
第1页 / 共4页
c#操作xml的完整例子.pdf_第2页
第2页 / 共4页
c#操作xml的完整例子.pdf_第3页
第3页 / 共4页
c#操作xml的完整例子.pdf_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
资源描述

《c#操作xml的完整例子.pdf》由会员分享,可在线阅读,更多相关《c#操作xml的完整例子.pdf(4页珍藏版)》请在三一文库上搜索。

1、这是一个用c# 控制台程序下,用 XmlDocument 进行 XML 操作的的例子,包含了查询、 增加、修改、删除、保存的基本操作。较完整的描述了一个XML 的整个操作流程。适合刚 入门 .net XML 操作的朋友参考和学习。 假设有 XML 文件: books.xml 哈里波特 10 这是一本很好看的书。 三国演义 10 四大名著之一。 水浒 6 四大名著之一。 红楼 5 四大名著之一。 下面是为 Program.cs using System; using System.Collections.Generic; using System.Text; using System.Xml;

2、namespace TestXml class Program staticvoid Main( string args) XmlElement theBook = null , theElem = null , root = null ; XmlDocument xmldoc = new XmlDocument(); try xmldoc.Load(“Books.xml“); root = xmldoc.DocumentElement; /- 新建一本书开始 - theBook = xmldoc.CreateElement(“book“); theElem = xmldoc.CreateEl

3、ement(“name“); theElem.InnerText = “新书“; theBook.AppendChild(theElem); theElem = xmldoc.CreateElement(“price“); theElem.InnerText = “20“; theBook.AppendChild(theElem); theElem = xmldoc.CreateElement(“memo“); theElem.InnerText = “新书更好看。 “; theBook.AppendChild(theElem); root.AppendChild(theBook); Cons

4、ole.Out.WriteLine(“- 新建一本书开始 -“); Console.Out.WriteLine(root.OuterXml); /- 新建一本书完成 - /- 下面对哈里波特做一些修改。 - /- 查询找哈里波特 - theBook = (XmlElement)root.SelectSingleNode(“/books /bookname= 哈里波特 “); Console.Out.WriteLine(“- 查找哈里波特 -“); Console.Out.WriteLine(theBook.OuterXml); /- 此时修改这本书的价格 - theBook.GetElemen

5、tsByTagName(“price“).Item(0).Inner Text = “15“;/getElementsByTagName 返回的是 NodeList ,所以要跟上 item (0) 。另外, GetElementsByTagName(“price“) 相当于 SelectNodes(“./price “) 。 Console.Out.WriteLine(“- 此时修改这本书的价格 - -“); Console.Out.WriteLine(theBook.OuterXml); /- 另外还想加一个属性id ,值为 B01 - theBook.SetAttribute(“id“,

6、“B01“); Console.Out.WriteLine(“- 另外还想加一个属性id , 值为 B01 -“); Console.Out.WriteLine(theBook.OuterXml); /- 对哈里波特修改完成。 - /- 再将所有价格低于10 的书删除 - theBook = (XmlElement)root.SelectSingleNode(“/books /bookid=B02“); Console.Out.WriteLine(“- 要用 id 属性删除三国演 义这本书 -“); Console.Out.WriteLine(theBook.OuterXml); theBoo

7、k.ParentNode.RemoveChild(theBook); Console.Out.WriteLine(“- 删除后的 -“); Console.Out.WriteLine(xmldoc.OuterXml); /- 再将所有价格低于10 的书删除 - XmlNodeList someBooks = root.SelectNodes(“/books/bo okprice10“); Console.Out.WriteLine(“- 再将所有价格低于10的书 删除 -“); Console.Out.WriteLine(“- 符合条件的书有“ + som eBooks.Count + “本。 -“); for ( int i = 0; i someBooks.Count; i+) someBooks.Item(i).ParentNode.RemoveChild(someBo oks.Item(i); Console.Out.WriteLine(“- 删除后的 -“); Console.Out.WriteLine(xmldoc.OuterXml); xmldoc.Save(“books.xml“);/ 保存到 books.xml Console.In.Read(); catch (Exception e) Console.Out.WriteLine(e.Message);

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1