C#操作XML(二)

 

 

2,添加結點:  

XmlDocument xmlDoc=new XmlDocument(); 
xmlDoc.Load(Server.MapPath("database.xml")); 
XmlNode rootElement=xmlDoc.SelectSingleNode("Websites");
//查找<Websites> 
XmlElement websiteElement=xmlDoc.CreateElement("Website");//創建一個<Website>節點 
websiteElement.SetAttribute("genre","www.cnzz.com");//設置該節點genre屬性 
websiteElement.SetAttribute("ISBN","1-1111-1");//設置該節點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.cnzz.com"; 
websiteElement.AppendChild(urlElement); 
rootElement.AppendChild(websiteElement);
//添加到<Websites>節點中 
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>
  
<Website genre="www.cnzz.com" ISBN="1-1111-1">
    
<title>站長統計</title>
    
<author>站長</author>
    
<url>http://www.cnzz.com</url>
  
</Website>
</Websites>

3,修改結點的值:

XmlDocument xmlDoc=new XmlDocument(); 
xmlDoc.Load( Server.MapPath("database.xml") ); 
XmlNodeList nodeList=xmlDoc.SelectSingleNode("Websites").ChildNodes;
//獲取Websites節點的所有子節點 
foreach(XmlNode xn in nodeList)//遍歷所有子節點 

    XmlElement xe=(XmlElement)xn;
//將子節點類型轉換爲XmlElement類型 
    if(xe.GetAttribute("genre")=="www.cnzz.com")//如果genre屬性值爲“www.cnzz.com” 
    { 
        xe.SetAttribute("genre","updatewww.cnzz.com");
//則修改該屬性爲“updatewww.cnzz.com” 
        XmlNodeList nls=xe.ChildNodes;//繼續獲取xe子節點的所有子節點 
        foreach(XmlNode xn1 in nls)//遍歷 
        { 
            XmlElement xe2=(XmlElement)xn1;
//轉換類型 
            if(xe2.Name=="author")//如果找到 
            { 
                xe2.InnerText="
作者";//則修改
            } 
        } 
    } 

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>
  
<Website genre="updatewww.cnzz.com" ISBN="1-1111-1">
    
<title>站長統計</title>
    
<author>作者</author>
    
<url>http://www.cnzz.com</url>
  
</Website>
</Websites>

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