C# 操作xml基础整理【转】
因自己经常使用到,担心找不到文章,特复制一份过来了。
文章转自 https://www.cnblogs.com/guxia/p/8242483.html
1 using System.Xml; 2 //初始化一个xml实例 3 XmlDocument xml=new XmlDocument(); 4 5 //导入指定xml文件 6 xml.Load(path); 7 xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); 8 9 //指定一个节点 10 XmlNode root=xml.SelectSingleNode("/root"); 11 12 //获取节点下所有直接子节点 13 XmlNodeList childlist=root.ChildNodes; 14 15 //判断该节点下是否有子节点 16 root.HasChildNodes; 17 18 //获取同名同级节点集合 19 XmlNodeList nodelist=xml.SelectNodes("/Root/News"); 20 21 //生成一个新节点 22 XmlElement node=xml.CreateElement("News"); 23 24 //将节点加到指定节点下,作为其子节点 25 root.AppendChild(node); 26 27 //将节点加到指定节点下某个子节点前 28 root.InsertBefore(node,root.ChildeNodes[i]); 29 30 //为指定节点的新建属性并赋值 31 node.SetAttribute("id","11111"); 32 33 //为指定节点添加子节点 34 root.AppendChild(node); 35 36 //获取指定节点的指定属性值 37 string id=node.Attributes["id"].Value; 38 39 //获取指定节点中的文本 40 string content=node.InnerText; 41 42 //保存XML文件 43 string path=Server.MapPath("~/file/bookstore.xml"); 44 xml.Save(path); 45 //or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); 46 47 二、具体实例 48 49 在C#.net中如何操作XML 50 需要添加的命名空间: 51 using System.Xml; 52 53 定义几个公共对象: 54 XmlDocument xmldoc ; 55 XmlNode xmlnode ; 56 XmlElement xmlelem ; 57 58 1,创建到服务器同名目录下的xml文件: 59 60 61 方法一: 62 xmldoc = new XmlDocument ( ) ; 63 //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?> 64 XmlDeclaration xmldecl; 65 xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null); 66 xmldoc.AppendChild ( xmldecl); 67 68 //加入一个根元素 69 xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ; 70 xmldoc.AppendChild ( xmlelem ) ; 71 //加入另外一个元素 72 for(int i=1;i<3;i++) 73 { 74 75 XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees> 76 XmlElement xe1=xmldoc.CreateElement("Node");//创建一个<Node>节点 77 xe1.SetAttribute("genre","李赞红");//设置该节点genre属性 78 xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性 79 80 XmlElement xesub1=xmldoc.CreateElement("title"); 81 xesub1.InnerText="CS从入门到精通";//设置文本节点 82 xe1.AppendChild(xesub1);//添加到<Node>节点中 83 XmlElement xesub2=xmldoc.CreateElement("author"); 84 xesub2.InnerText="候捷"; 85 xe1.AppendChild(xesub2); 86 XmlElement xesub3=xmldoc.CreateElement("price"); 87 xesub3.InnerText="58.3"; 88 xe1.AppendChild(xesub3); 89 90 root.AppendChild(xe1);//添加到<Employees>节点中 91 } 92 //保存创建好的XML文档 93 xmldoc.Save ( Server.MapPath("data.xml") ) ; 94 95 ////////////////////////////////////////////////////////////////////////////////////// 96 结果:在同名目录下生成了名为data.xml的文件,内容如下, 97 <?xml version="1.0" encoding="gb2312"?> 98 <Employees> 99 <Node genre="李赞红" ISBN="2-3631-4"> 100 <title>CS从入门到精通</title> 101 <author>候捷</author> 102 <price>58.3</price> 103 </Node> 104 <Node genre="李赞红" ISBN="2-3631-4"> 105 <title>CS从入门到精通</title> 106 <author>候捷</author> 107 <price>58.3</price> 108 </Node> 109 </Employees> 110 111 112 方法二: 113 XmlTextWriter xmlWriter; 114 string strFilename = Server.MapPath("data1.xml") ; 115 116 xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档 117 xmlWriter.Formatting = Formatting.Indented; 118 xmlWriter.WriteStartDocument(); 119 xmlWriter.WriteStartElement("Employees"); 120 121 xmlWriter.WriteStartElement("Node"); 122 xmlWriter.WriteAttributeString("genre","李赞红"); 123 xmlWriter.WriteAttributeString("ISBN","2-3631-4"); 124 125 xmlWriter.WriteStartElement("title"); 126 xmlWriter.WriteString("CS从入门到精通"); 127 xmlWriter.WriteEndElement(); 128 129 xmlWriter.WriteStartElement("author"); 130 xmlWriter.WriteString("候捷"); 131 xmlWriter.WriteEndElement(); 132 133 xmlWriter.WriteStartElement("price"); 134 xmlWriter.WriteString("58.3"); 135 xmlWriter.WriteEndElement(); 136 137 xmlWriter.WriteEndElement(); 138 139 xmlWriter.Close(); 140 ////////////////////////////////////////////////////////////////////////////////////// 141 结果: 142 <?xml version="1.0" encoding="gb2312"?> 143 <Employees> 144 <Node genre="李赞红" ISBN="2-3631-4"> 145 <title>CS从入门到精通</title> 146 <author>候捷</author> 147 <price>58.3</price> 148 </Node> 149 </Employees> 150 151 2,添加一个结点: 152 153 XmlDocument xmlDoc=new XmlDocument(); 154 xmlDoc.Load(Server.MapPath("data.xml")); 155 XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees> 156 XmlElement xe1=xmlDoc.CreateElement("Node");//创建一个<Node>节点 157 xe1.SetAttribute("genre","张三");//设置该节点genre属性 158 xe1.SetAttribute("ISBN","1-1111-1");//设置该节点ISBN属性 159 160 XmlElement xesub1=xmlDoc.CreateElement("title"); 161 xesub1.InnerText="C#入门帮助";//设置文本节点 162 xe1.AppendChild(xesub1);//添加到<Node>节点中 163 XmlElement xesub2=xmlDoc.CreateElement("author"); 164 xesub2.InnerText="高手"; 165 xe1.AppendChild(xesub2); 166 XmlElement xesub3=xmlDoc.CreateElement("price"); 167 xesub3.InnerText="158.3"; 168 xe1.AppendChild(xesub3); 169 170 root.AppendChild(xe1);//添加到<Employees>节点中 171 xmlDoc.Save ( Server.MapPath("data.xml") ); 172 173 ////////////////////////////////////////////////////////////////////////////////////// 174 结果:在xml原有的内容里添加了一个结点,内容如下, 175 <?xml version="1.0" encoding="gb2312"?> 176 <Employees> 177 <Node genre="李赞红" ISBN="2-3631-4"> 178 <title>CS从入门到精通</title> 179 <author>候捷</author> 180 <price>58.3</price> 181 </Node> 182 <Node genre="李赞红" ISBN="2-3631-4"> 183 <title>CS从入门到精通</title> 184 <author>候捷</author> 185 <price>58.3</price> 186 </Node> 187 <Node genre="张三" ISBN="1-1111-1"> 188 <title>C#入门帮助</title> 189 <author>高手</author> 190 <price>158.3</price> 191 </Node> 192 </Employees> 193 194 3,修改结点的值(属性和子结点): 195 196 XmlDocument xmlDoc=new XmlDocument(); 197 xmlDoc.Load( Server.MapPath("data.xml") ); 198 199 XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点 200 201 foreach(XmlNode xn in nodeList)//遍历所有子节点 202 { 203 XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型 204 if(xe.GetAttribute("genre")=="张三")//如果genre属性值为“张三” 205 { 206 xe.SetAttribute("genre","update张三");//则修改该属性为“update张三” 207 208 XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点 209 foreach(XmlNode xn1 in nls)//遍历 210 { 211 XmlElement xe2=(XmlElement)xn1;//转换类型 212 if(xe2.Name=="author")//如果找到 213 { 214 xe2.InnerText="亚胜";//则修改 215 } 216 } 217 } 218 } 219 xmlDoc.Save( Server.MapPath("data.xml") );//保存。 220 221 ////////////////////////////////////////////////////////////////////////////////////// 222 结果:将原来的所有结点的信息都修改了,xml的内容如下, 223 <?xml version="1.0" encoding="gb2312"?> 224 <Employees> 225 <Node genre="李赞红" ISBN="2-3631-4"> 226 <title>CS从入门到精通</title> 227 <author>候捷</author> 228 <price>58.3</price> 229 </Node> 230 <Node genre="李赞红" ISBN="2-3631-4"> 231 <title>CS从入门到精通</title> 232 <author>候捷</author> 233 <price>58.3</price> 234 </Node> 235 <Node genre="update张三" ISBN="1-1111-1"> 236 <title>C#入门帮助</title> 237 <author>亚胜</author> 238 <price>158.3</price> 239 </Node> 240 </Employees> 241 242 4,修改结点(添加结点的属性和添加结点的自结点): 243 XmlDocument xmlDoc=new XmlDocument(); 244 xmlDoc.Load( Server.MapPath("data.xml") ); 245 246 XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点 247 248 foreach(XmlNode xn in nodeList) 249 { 250 XmlElement xe=(XmlElement)xn; 251 xe.SetAttribute("test","111111"); 252 253 XmlElement xesub=xmlDoc.CreateElement("flag"); 254 xesub.InnerText="1"; 255 xe.AppendChild(xesub); 256 } 257 xmlDoc.Save( Server.MapPath("data.xml") ); 258 259 ////////////////////////////////////////////////////////////////////////////////////// 260 结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下, 261 <?xml version="1.0" encoding="gb2312"?> 262 <Employees> 263 <Node genre="李赞红" ISBN="2-3631-4" test="111111"> 264 <title>CS从入门到精通</title> 265 <author>候捷</author> 266 <price>58.3</price> 267 <flag>1</flag> 268 </Node> 269 <Node genre="李赞红" ISBN="2-3631-4" test="111111"> 270 <title>CS从入门到精通</title> 271 <author>候捷</author> 272 <price>58.3</price> 273 <flag>1</flag> 274 </Node> 275 <Node genre="update张三" ISBN="1-1111-1" test="111111"> 276 <title>C#入门帮助</title> 277 <author>亚胜</author> 278 <price>158.3</price> 279 <flag>1</flag> 280 </Node> 281 </Employees> 282 283 5,删除结点中的某一个属性: 284 XmlDocument xmlDoc=new XmlDocument(); 285 xmlDoc.Load( Server.MapPath("data.xml") ); 286 XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 287 foreach(XmlNode xn in xnl) 288 { 289 XmlElement xe=(XmlElement)xn; 290 xe.RemoveAttribute("genre");//删除genre属性 291 292 XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点 293 foreach(XmlNode xn1 in nls)//遍历 294 { 295 XmlElement xe2=(XmlElement)xn1;//转换类型 296 if(xe2.Name=="flag")//如果找到 297 { 298 xe.RemoveChild(xe2);//则删除 299 } 300 } 301 } 302 xmlDoc.Save( Server.MapPath("data.xml") ); 303 304 //////////////////////////////////////////////////////////////////////////////////////] 305 结果:删除了结点的一个属性和结点的一个子结点,内容如下, 306 <?xml version="1.0" encoding="gb2312"?> 307 <Employees> 308 <Node ISBN="2-3631-4" test="111111"> 309 <title>CS从入门到精通</title> 310 <author>候捷</author> 311 <price>58.3</price> 312 </Node> 313 <Node ISBN="2-3631-4" test="111111"> 314 <title>CS从入门到精通</title> 315 <author>候捷</author> 316 <price>58.3</price> 317 </Node> 318 <Node ISBN="1-1111-1" test="111111"> 319 <title>C#入门帮助</title> 320 <author>亚胜</author> 321 <price>158.3</price> 322 </Node> 323 </Employees> 324 325 6,删除结点: 326 XmlDocument xmlDoc=new XmlDocument(); 327 xmlDoc.Load( Server.MapPath("data.xml") ); 328 XmlNode root=xmlDoc.SelectSingleNode("Employees"); 329 XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 330 for(int i=0;i<xnl.Count;i++) 331 { 332 XmlElement xe=(XmlElement)xnl.Item(i); 333 if(xe.GetAttribute("genre")=="张三") 334 { 335 root.RemoveChild(xe); 336 if(i<xnl.Count)i=i-1; 337 } 338 } 339 xmlDoc.Save( Server.MapPath("data.xml") ); 340 341 //////////////////////////////////////////////////////////////////////////////////////] 342 结果:删除了符合条件的所有结点,原来的内容: 343 344 <?xml version="1.0" encoding="gb2312"?> 345 <Employees> 346 <Node genre="李赞红" ISBN="2-3631-4"> 347 <title>CS从入门到精通</title> 348 <author>候捷</author> 349 <price>58.3</price> 350 </Node> 351 <Node genre="李赞红" ISBN="2-3631-4"> 352 <title>CS从入门到精通</title> 353 <author>候捷</author> 354 <price>58.3</price> 355 </Node> 356 <Node genre="张三" ISBN="1-1111-1"> 357 <title>C#入门帮助</title> 358 <author>高手</author> 359 <price>158.3</price> 360 </Node> 361 <Node genre="张三" ISBN="1-1111-1"> 362 <title>C#入门帮助</title> 363 <author>高手</author> 364 <price>158.3</price> 365 </Node> 366 </Employees> 367 368 删除后的内容: 369 <?xml version="1.0" encoding="gb2312"?> 370 <Employees> 371 <Node genre="李赞红" ISBN="2-3631-4"> 372 <title>CS从入门到精通</title> 373 <author>候捷</author> 374 <price>58.3</price> 375 </Node> 376 <Node genre="李赞红" ISBN="2-3631-4"> 377 <title>CS从入门到精通</title> 378 <author>候捷</author> 379 <price>58.3</price> 380 </Node> 381 </Employees> 382 383 7,按照文本文件读取xml 384 385 System.IO.StreamReader myFile =new 386 System.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default); 387 //注意System.Text.Encoding.Default 388 389 string myString = myFile.ReadToEnd();//myString是读出的字符串 390 myFile.Close(); 391 392 三、高级应用 393 394 /*读取xml数据 两种xml方式*/ 395 <aaa> 396 <bb>something</bb> 397 <cc>something</cc> 398 </aaa> 399 400 <aaa> 401 <add key="123" value="321"/> 402 </aaa> 403 404 /*第一种方法*/ 405 DS.ReadXml("your xmlfile name"); 406 Container.DataItem("bb"); 407 Container.DataItem("cc"); 408 DS.ReadXmlSchema("your xmlfile name"); 409 410 /*第二种方法*/ 411 <aaa> 412 <add key="123" value="321"/> 413 </aaa> 414 如果我要找到123然后取到321应该怎么写呢? 415 416 using System.XML; 417 XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); 418 xmlDoc.Load(@"c:/Config.xml"); 419 XmlElement elem = xmlDoc.GetElementById("add"); 420 string str = elem.Attributes["value"].Value 421 422 423 /*第三种方法: SelectSingleNode 读取两种格式的xml *---/ 424 -------------------------------------------------------------------- 425 <?xml version="1.0" encoding="utf-8" ?> 426 <configuration> 427 <appSettings> 428 <ConnectionString>Data Source=yf; user id=ctm_dbo;password=123</ConnectionString> 429 </appSettings> 430 </configuration> 431 -------------------------------------------------------------------------- 432 XmlDocument doc = new XmlDocument(); 433 doc.Load(strXmlName); 434 435 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString"); 436 if(node!=null) 437 { 438 string k1=node.Value; //null 439 string k2=node.InnerText;//Data Source=yf; user id=ctm_dbo;password=123 440 string k3=node.InnerXml;//Data Source=yf; user id=ctm_dbo;password=123 441 node=null; 442 } 443 444 ******************************************************************** 445 <?xml version="1.0" encoding="utf-8" ?> 446 <configuration> 447 <appSettings> 448 <add key="ConnectionString" value="Data Source=yf; user id=ctm_dbo;password=123" /> 449 </appSettings> 450 </configuration> 451 **--------------------------------------------------------------------** 452 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add"); 453 if(node!=null) 454 { 455 string k=node.Attributes["key"].Value; 456 string v=node.Attributes["value"].Value; 457 node=null; 458 } 459 *--------------------------------------------------------------------* 460 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add"); 461 if(node!=null) 462 { 463 XmlNodeReader nr=new XmlNodeReader(node); 464 nr.MoveToContent(); 465 //检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。 466 nr.MoveToAttribute("value"); 467 string s=nr.Value; 468 node=null; 469 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端