概述C#.NET操作XML
作者:佚名
本文介紹C#.NET操作XML,包括介紹添加的命名空間、定義幾個(gè)公共對(duì)象、創(chuàng)建到服務(wù)器同名目錄下的xml文件和生成了名為data.xml的文件。
如何讓C#.NET操作XML?需要添加的命名空間:
- using System.Xml;
要完成C#.NET操作XML,首先定義幾個(gè)公共對(duì)象:
- XmlDocument xmldoc ;
- XmlNode xmlnode ;
- XmlElement xmlelem ;
創(chuàng)建到服務(wù)器同名目錄下的xml文件:
- xmldoc = new XmlDocument ( ) ;
- //加入XML的聲明段落
- xmlnode = xmldoc.CreateNode ( XmlNodeType.XmlDeclaration , "" , "" ) ;
- xmldoc.AppendChild ( xmlnode ) ;
- //加入一個(gè)根元素
- xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ;
- xmldoc.AppendChild ( xmlelem ) ;
- //加入另外一個(gè)元素
- for(int i=1;i<3;i )
- {
- XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees>
- XmlElement xe1=xmldoc.CreateElement("Node");//創(chuàng)建一個(gè)<Node>節(jié)點(diǎn)
- xe1.SetAttribute("genre","李贊紅");//設(shè)置該節(jié)點(diǎn)genre屬性
- xe1.SetAttribute("ISBN","2-3631-4");//設(shè)置該節(jié)點(diǎn)ISBN屬性
- XmlElement xesub1=xmldoc.CreateElement("title");
- xesub1.InnerText="CS從入門(mén)到精通";//設(shè)置文本節(jié)點(diǎn)
- xe1.AppendChild(xesub1);//添加到<Node>節(jié)點(diǎn)中
- 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>節(jié)點(diǎn)中
- }
- //保存創(chuàng)建好的XML文檔
- xmldoc.Save ( Server.MapPath("data.xml") ) ;
結(jié)果:在同名目錄下生成了名為data.xml的文件,內(nèi)容如下
- <?xml version="1.0"?>
- <Employees>
- <Node genre="李贊紅" ISBN="2-3631-4">
- <title>CS從入門(mén)到精通</title>
- <author>候捷</author>
- <price>58.3</price>
- </Node>
- <Node genre="李贊紅" ISBN="2-3631-4">
- <title>CS從入門(mén)到精通</title>
- <author>候捷</author>
- <price>58.3</price>
- </Node>
- </Employees>
以上介紹C#.NET操作XML。
【編輯推薦】
責(zé)任編輯:佚名
來(lái)源:
比特網(wǎng)