本文将重点介绍如何在ASP.net(C#)下操作XML文件。
1,创建xml文件:
代码:
XmlDocument xmldoc = new XmlDocument ( ) ;
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);
xmldoc.AppendChild ( xmldecl);
//加入一个根元素
XmlElement xmlelem = xmldoc.CreateElement( "" , "Websites" , "" ) ;
xmldoc.AppendChild ( xmlelem ) ;
//加入另外一个元素
for(int i=1;i<3;i++)
{
XmlNode rootElement=xmldoc.SelectSingleNode("Websites");//查找<Websites>
XmlElement websiteElement=xmldoc.CreateElement("Website");//创建一个<Website>节点
websiteElement.SetAttribute("genre","www.chinaz.com");//设置该节点genre属性
websiteElement.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性
XmlElement titleElement=xmldoc.CreateElement("title");
titleElement.InnerText="中国站长站";//设置文本节点
websiteElement.AppendChild(titleElement);//添加到<Website>节点中
XmlElement authorElement=xmldoc.CreateElement("author");
authorElement.InnerText="作者";
websiteElement.AppendChild(authorElement);
XmlElement urlElement=xmldoc.CreateElement("url");
urlElement.InnerText="http://www.chinaz.com";
websiteElement.AppendChild(urlElement);
rootElement.AppendChild(websiteElement);//添加到<Websites>节点中
}
//保存创建好的XML文档
xmldoc.Save ( Server.MapPath("database.xml") ) ;
结果:
<?xml version="1.0" encoding="gb2312"?>
<Websites>
<Website genre="www.chinaz.com" ISBN="2-3631-4">
<title>中国站长站</title>
<author>作者</author>
<url>http://www.chinaz.com</url>
</Website>
<Website genre="www.chinaz.com" ISBN="2-3631-4">
<title>中国站长站</title>
<author>作者</author>
<url>http://www.chinaz.com</url>
</Website>
</Websites>