C#操作XML方法详解
using System.Xml;
//初始化一个xml实例XmlDocument xml=new XmlDocument();//导入指定xml文件xml.Load(path);xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));//指定一个节点XmlNode root=xml.SelectSingleNode("/root");//获取节点下所有直接子节点XmlNodeList childlist=root.ChildNodes;//判断该节点下是否有子节点root.HasChildNodes;//获取同名同级节点集合XmlNodeList nodelist=xml.SelectNodes("/Root/News");//生成一个新节点XmlElement node=xml.CreateElement("News");//将节点加到指定节点下,作为其子节点root.AppendChild(node);//将节点加到指定节点下某个子节点前root.InsertBefore(node,root.ChildeNodes[i]);//为指定节点的新建属性并赋值node.SetAttribute("id","11111");//为指定节点添加子节点root.AppendChild(node);//获取指定节点的指定属性值string id=node.Attributes["id"].Value;//获取指定节点中的文本string content=node.InnerText;//保存XML文件string path=Server.MapPath("~/file/bookstore.xml");xml.Save(path);//or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));二、具体实例在C#.net中如何操作XML需要添加的命名空间:using System.Xml;定义几个公共对象:XmlDocument xmldoc ;XmlNode xmlnode ;XmlElement xmlelem ;1,创建到服务器同名目录下的xml文件:方法一:xmldoc = new XmlDocument ( ) ;//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>XmlDeclaration xmldecl; xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null); xmldoc.AppendChild ( xmldecl);//加入一个根元素xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ;xmldoc.AppendChild ( xmlelem ) ;//加入另外一个元素for(int i=1;i<3;i++){XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees>XmlElement xe1=xmldoc.CreateElement("Node");//创建一个<Node>节点xe1.SetAttribute("genre","李赞红");//设置该节点genre属性xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性XmlElement xesub1=xmldoc.CreateElement("title");xesub1.InnerText="CS从入门到精通";//设置文本节点xe1.AppendChild(xesub1);//添加到<Node>节点中XmlElement xesub2=xmldoc.CreateElement("author");xesub2.InnerText="候捷";xe1.AppendChild(xesub2);XmlElement xesub3=xmldoc.CreateElement("price");xesub3.InnerText="58.3";xe1.AppendChild(xesub3);root.AppendChild(xe1);//添加到<Employees>节点中}//保存创建好的XML文档xmldoc.Save ( Server.MapPath("data.xml") ) ;//////////////////////////////////////////////////////////////////////////////////////结果:在同名目录下生成了名为data.xml的文件,内容如下,<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node></Employees>方法二:XmlTextWriter xmlWriter; string strFilename = Server.MapPath("data1.xml") ; xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档 xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Employees"); xmlWriter.WriteStartElement("Node"); xmlWriter.WriteAttributeString("genre","李赞红"); xmlWriter.WriteAttributeString("ISBN","2-3631-4"); xmlWriter.WriteStartElement("title"); xmlWriter.WriteString("CS从入门到精通"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("author"); xmlWriter.WriteString("候捷"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("price"); xmlWriter.WriteString("58.3"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.Close();//////////////////////////////////////////////////////////////////////////////////////结果:<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node></Employees>2,添加一个结点:XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load(Server.MapPath("data.xml"));XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees>XmlElement xe1=xmlDoc.CreateElement("Node");//创建一个<Node>节点xe1.SetAttribute("genre","张三");//设置该节点genre属性xe1.SetAttribute("ISBN","1-1111-1");//设置该节点ISBN属性XmlElement xesub1=xmlDoc.CreateElement("title");xesub1.InnerText="C#入门帮助";//设置文本节点xe1.AppendChild(xesub1);//添加到<Node>节点中XmlElement xesub2=xmlDoc.CreateElement("author");xesub2.InnerText="高手";xe1.AppendChild(xesub2);XmlElement xesub3=xmlDoc.CreateElement("price");xesub3.InnerText="158.3";xe1.AppendChild(xesub3);root.AppendChild(xe1);//添加到<Employees>节点中xmlDoc.Save ( Server.MapPath("data.xml") );//////////////////////////////////////////////////////////////////////////////////////结果:在xml原有的内容里添加了一个结点,内容如下,<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="张三" ISBN="1-1111-1"> <title>C#入门帮助</title> <author>高手</author> <price>158.3</price> </Node></Employees>3,修改结点的值(属性和子结点):XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load( Server.MapPath("data.xml") );XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点foreach(XmlNode xn in nodeList)//遍历所有子节点{XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型if(xe.GetAttribute("genre")=="张三")//如果genre属性值为“张三”{xe.SetAttribute("genre","update张三");//则修改该属性为“update张三”XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点foreach(XmlNode xn1 in nls)//遍历{XmlElement xe2=(XmlElement)xn1;//转换类型if(xe2.Name=="author")//如果找到{xe2.InnerText="亚胜";//则修改}}}}xmlDoc.Save( Server.MapPath("data.xml") );//保存。//////////////////////////////////////////////////////////////////////////////////////结果:将原来的所有结点的信息都修改了,xml的内容如下,<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="update张三" ISBN="1-1111-1"> <title>C#入门帮助</title> <author>亚胜</author> <price>158.3</price> </Node></Employees>4,修改结点(添加结点的属性和添加结点的自结点):XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load( Server.MapPath("data.xml") );XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点foreach(XmlNode xn in nodeList){XmlElement xe=(XmlElement)xn;xe.SetAttribute("test","111111");XmlElement xesub=xmlDoc.CreateElement("flag");xesub.InnerText="1";xe.AppendChild(xesub);}xmlDoc.Save( Server.MapPath("data.xml") );//////////////////////////////////////////////////////////////////////////////////////结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下,<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4" test="111111"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="李赞红" ISBN="2-3631-4" test="111111"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="update张三" ISBN="1-1111-1" test="111111"> <title>C#入门帮助</title> <author>亚胜</author> <price>158.3</price> <flag>1</flag> </Node></Employees>5,删除结点中的某一个属性:XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load( Server.MapPath("data.xml") );XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;foreach(XmlNode xn in xnl){XmlElement xe=(XmlElement)xn;xe.RemoveAttribute("genre");//删除genre属性XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点foreach(XmlNode xn1 in nls)//遍历{XmlElement xe2=(XmlElement)xn1;//转换类型if(xe2.Name=="flag")//如果找到{xe.RemoveChild(xe2);//则删除}}}xmlDoc.Save( Server.MapPath("data.xml") );//////////////////////////////////////////////////////////////////////////////////////]结果:删除了结点的一个属性和结点的一个子结点,内容如下,<?xml version="1.0" encoding="gb2312"?><Employees> <Node ISBN="2-3631-4" test="111111"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node ISBN="2-3631-4" test="111111"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node ISBN="1-1111-1" test="111111"> <title>C#入门帮助</title> <author>亚胜</author> <price>158.3</price> </Node></Employees>6,删除结点:XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load( Server.MapPath("data.xml") );XmlNode root=xmlDoc.SelectSingleNode("Employees");XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;for(int i=0;i<xnl.Count;i++){XmlElement xe=(XmlElement)xnl.Item(i);if(xe.GetAttribute("genre")=="张三"){root.RemoveChild(xe);if(i<xnl.Count)i=i-1;}}xmlDoc.Save( Server.MapPath("data.xml") );//////////////////////////////////////////////////////////////////////////////////////]结果:删除了符合条件的所有结点,原来的内容:<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="张三" ISBN="1-1111-1"> <title>C#入门帮助</title> <author>高手</author> <price>158.3</price> </Node> <Node genre="张三" ISBN="1-1111-1"> <title>C#入门帮助</title> <author>高手</author> <price>158.3</price> </Node></Employees>删除后的内容:<?xml version="1.0" encoding="gb2312"?><Employees> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node> <Node genre="李赞红" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </Node></Employees> 7,按照文本文件读取xmlSystem.IO.StreamReader myFile =newSystem.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default);//注意System.Text.Encoding.Defaultstring myString = myFile.ReadToEnd();//myString是读出的字符串myFile.Close();三、高级应用/*读取xml数据 两种xml方式*/<aaa> <bb>something</bb> <cc>something</cc></aaa> <aaa> <add key="123" value="321"/></aaa>/*第一种方法*/DS.ReadXml("your xmlfile name");Container.DataItem("bb");Container.DataItem("cc");DS.ReadXmlSchema("your xmlfile name"); /*第二种方法*/<aaa> <add key="123" value="321"/></aaa>如果我要找到123然后取到321应该怎么写呢? using System.XML;XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument();xmlDoc.Load(@"c:/Config.xml");XmlElement elem = xmlDoc.GetElementById("add");string str = elem.Attributes["value"].Value /*第三种方法: SelectSingleNode 读取两种格式的xml *---/--------------------------------------------------------------------<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <ConnectionString>Data Source=yf; user id=ctm_dbo;password=123</ConnectionString> </appSettings></configuration>--------------------------------------------------------------------------XmlDocument doc = new XmlDocument();doc.Load(strXmlName); XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString"); if(node!=null) { string k1=node.Value; //null string k2=node.InnerText;//Data Source=yf; user id=ctm_dbo;password=123 string k3=node.InnerXml;//Data Source=yf; user id=ctm_dbo;password=123 node=null; } ********************************************************************<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="ConnectionString" value="Data Source=yf; user id=ctm_dbo;password=123" /> </appSettings></configuration>**--------------------------------------------------------------------** XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add"); if(node!=null) { string k=node.Attributes["key"].Value; string v=node.Attributes["value"].Value; node=null; }*--------------------------------------------------------------------* XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add"); if(node!=null) { XmlNodeReader nr=new XmlNodeReader(node); nr.MoveToContent(); //检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。 nr.MoveToAttribute("value"); string s=nr.Value; node=null; }C#操作XML方法详解的更多相关文章
- Cookie介绍及JavaScript操作Cookie方法详解
本文主要为大家简单介绍了以下Cookie的用途.运行机制,以及JavaScript操作Cookie的各种方法,总结的比较全面,希望能给大家带来帮助. 什么是 Cookie “cookie 是存储于访问 ...
- 关于laravel5.4.12新增集合操作when方法详解
从v5.4.12开始,Laravel Collections现在包括一个when方法,允许您对项目执行条件操作,而不会中断链. 像所有其他Laravel 集合方法,这一个可以有很多用例,选择其中一个例 ...
- Python的循环正确的操作使用方法详解
要计算1+2+3,我们可以直接写表达式: >>> 1 + 2 + 3 6 要计算1+2+3+...+10,勉强也能写出来. 但是,要计算1+2+3+...+10000,直接写表达式就 ...
- 使用Java操作文本文件的方法详解
使用Java操作文本文件的方法详解 摘要: 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而 ...
- Python操作SQLite数据库的方法详解
Python操作SQLite数据库的方法详解 本文实例讲述了Python操作SQLite数据库的方法.分享给大家供大家参考,具体如下: SQLite简单介绍 SQLite数据库是一款非常小巧的嵌入式开 ...
- HTTP请求方法详解
HTTP请求方法详解 请求方法:指定了客户端想对指定的资源/服务器作何种操作 下面我们介绍HTTP/1.1中可用的请求方法: [GET:获取资源] GET方法用来请求已被URI识别的资源.指定 ...
- [转]AndroidManifest.xml文件详解
转自:http://www.cnblogs.com/greatverve/archive/2012/05/08/AndroidManifest-xml.html AndroidManifest.xml ...
- Android源码下载方法详解
转自:http://www.cnblogs.com/anakin/archive/2011/12/20/2295276.html Android源码下载方法详解 相信很多下载过内核的人都对这个很熟悉 ...
- $.ajax()方法详解 jquery
$.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...
随机推荐
- 2018/09/13《涂抹MySQL》【MySQL复制特性】学习笔记(六)
推荐一首歌 - <可不可以>张紫豪 好吧,随便从排行榜上找了一首 读 第十一章<MySQL的复制特性> 总结 1:复制(Replication) 应用场景? - 提高性能 (通 ...
- 《mongoDB》概念-数据类型
一:概念 - mongoDB 是一个面向文档的数据库,而不是关系型数据库. - 摘自<mongoDB 权威指南 第2版>第3页 二:数据类型 - null - 用于表示空值或者不存在的字段 ...
- numpy——.npy和.npz文件
npy文件--Numpy专用的二进制格式np.load()和np.save()是读写磁盘数组数据的两个重要函数.使用时,数组会以未压缩的原始二进制格式保存在扩展名为.npy的文件中. import n ...
- Bootstrap3隐藏滑动侧边栏菜单代码特效
链接:https://pan.baidu.com/s/1syV3ZFg-RqfCv0HS5K0vug 提取码:yjex
- 洛谷P3354 Riv河流 [IOI2005] 树型dp
正解:树型dp 解题报告: 传送门! 简要题意:有棵树,每个节点有个权值w,要求选k个节点,最大化∑dis*w,其中如果某个节点到根的路径上选了别的节点,dis指的是到达那个节点的距离 首先这个一看就 ...
- SRWebSocket
以前有个项目里有做聊天室,就是用的SRWebSocket.现在整理下资料,主要是对网上搜索到的资料进行整合. WebSocket介绍,与Socket的区别 https://blog.csdn.net/ ...
- 谈谈javascript数组排序方法sort()的使用,重点介绍参数使用及内部机制?
语法:arrayObject.sort(sortby) 参数sortby可选,规定排序顺序,必须是函数: 注:如果调用该方法时没有使用参数,将按字符编码的顺序进行排序,要实现这一点,首先应把数组的元素 ...
- 安装Vue Devtools
命令行进入vue-devtools\vue-devtools-master执行 cnpm install (貌似npm不太好使,也可能是我网络代理的原因) (淘宝镜像安装 npm install -- ...
- Mac本如何卸载MySQL
Mac本如何卸载MySQL 在Mac上卸载MySQL上一件非常麻烦的事,如果没有卸载干净,就会无法安装新的MySQL 怎样才能完全卸载MySQL呢?(包括所有数据库) 执行以下操作: #打开终端 ...
- Java通过POI生成Excel
import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; impo ...