資源描述:
《C# 對(duì)XML操作入門實(shí)例》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、C#對(duì)XML操作入門實(shí)例已知有一個(gè)XML文件(bookstore.xml)如下:復(fù)制代碼代碼如下:Oberon'sLegacyCorets,Eva5.951、往節(jié)點(diǎn)中插入一個(gè)節(jié)點(diǎn):復(fù)制代碼代碼如下:XmlDocumentxmlDoc
2、=newXmlDocument();xmlDoc.Load("bookstore.xml");XmlNoderoot=xmlDoc.SelectSingleNode("bookstore");//查找XmlElementxe1=xmlDoc.createElement_x("book");//創(chuàng)建一個(gè)節(jié)點(diǎn)xe1.SetAttribute("genre","李贊紅");//設(shè)置該節(jié)點(diǎn)genre屬性xe1.SetAttribute("ISBN","2-3631-4");//設(shè)置該節(jié)點(diǎn)ISBN屬性XmlElementxesub1=x
3、mlDoc.createElement_x("title");xesub1.InnerText="CS從入門到精通";//設(shè)置文本節(jié)點(diǎn)xe1.AppendChild(xesub1);//添加到節(jié)點(diǎn)中XmlElementxesub2=xmlDoc.createElement_x("author");xesub2.InnerText="候捷";xe1.AppendChild(xesub2);XmlElementxesub3=xmlDoc.createElement_x("price");xesub3.InnerText="58.3";xe1.Appen
4、dChild(xesub3);root.AppendChild(xe1);//添加到節(jié)點(diǎn)中xmlDoc.Save("bookstore.xml");//================結(jié)果為:復(fù)制代碼代碼如下:Oberon'sLegacyCorets,Eva5.95<
5、bookgenre="李贊紅"ISBN="2-3631-4">
CS從入門到精通候捷58.32、修改節(jié)點(diǎn):將genre屬性值為“李贊紅“的節(jié)點(diǎn)的genre值改為“update李贊紅”,將該節(jié)點(diǎn)的子節(jié)點(diǎn)
的文本修改為“亞勝”。復(fù)制代碼代碼如下:XmlNodeListnodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//獲取bookstore節(jié)點(diǎn)的所有子節(jié)點(diǎn)f6、oreach(XmlNodexninnodeList)//遍歷所有子節(jié)點(diǎn){XmlElementxe=(XmlElement)xn;//將子節(jié)點(diǎn)類型轉(zhuǎn)換為XmlElement類型if(xe.GetAttribute("genre")=="李贊紅")//如果genre屬性值為“李贊紅”{xe.SetAttribute("genre","update李贊紅");//則修改該屬性為“update李贊紅”XmlNodeListnls=xe.ChildNodes;//繼續(xù)獲取xe子節(jié)點(diǎn)的所有子節(jié)點(diǎn)foreach(XmlNodexn1innls)//遍歷{XmlElemen
7、txe2=(XmlElement)xn1;//轉(zhuǎn)換類型if(xe2.Name=="author")//如果找到{xe2.InnerText="亞勝";//則修改break;//找到退出來(lái)就可以了}}break;}}xmlDoc.Save("bookstore.xml");//保存。//=================最后結(jié)果為:復(fù)制代碼代碼如下:Oberon'sLegacy8、itle>Corets