C#操作XML(一)

 

 

本文將重點介紹如何在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> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章