建站學(xué)院(LieHuo.Net)xml文檔 使用js腳本添加、修改、刪除xml節(jié)點(diǎn),已知有一個(gè)XML文件(bookstore.xml)如下:
以下為引用的內(nèi)容: <?xml version="1.0" encoding="gb2312"?> <bookstore> <book genre="fantasy" ISBN="2-3631-4"> <title>Oberons Legacy</title> <author>Corets, Eva</author> <price>5.95</price> </book> </bookstore> |
1、往<bookstore>節(jié)點(diǎn)中插入一個(gè)<book>節(jié)點(diǎn):
以下為引用的內(nèi)容: XmlDocument xmlDoc=new XmlDocument(); xmlDoc.Load("bookstore.xml"); XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore> XmlElement xe1=xmlDoc.CreateElement("book");//創(chuàng)建一個(gè)<book>節(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"); root.AppendChild(xe1);//添加到<bookstore>節(jié)點(diǎn)中 |
以下為引用的內(nèi)容: <?xml version="1.0" encoding="gb2312"?> <bookstore> <book genre="fantasy" ISBN="2-3631-4"> <title>Oberons Legacy</title> <author>Corets, Eva</author> <price>5.95</price> </book> <book genre="作者" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>作者</author> <price>58.3</price> </book> </bookstore> |
2、修改節(jié)點(diǎn):將genre屬性值為“作者“的節(jié)點(diǎn)的genre值改為“update作者”,將該節(jié)點(diǎn)的子節(jié)點(diǎn)<author>的文本修改為“亞勝”。
以下為引用的內(nèi)容: XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//獲取bookstore節(jié)點(diǎn)的所有子節(jié)點(diǎn) foreach(XmlNode xn in nodeList)//遍歷所有子節(jié)點(diǎn) { XmlElement xe=(XmlElement)xn;//將子節(jié)點(diǎn)類型轉(zhuǎn)換為XmlElement類型 if(xe.GetAttribute("genre")=="作者")//如果genre屬性值為“作者” { xe.SetAttribute("genre","update作者");//則修改該屬性為“update作者” XmlNodeList nls=xe.ChildNodes;//繼續(xù)獲取xe子節(jié)點(diǎn)的所有子節(jié)點(diǎn) xmlDoc.Save("bookstore.xml");//保存。 |
以下為引用的內(nèi)容: <?xml version="1.0" encoding="gb2312"?> <bookstore> <book genre="fantasy" ISBN="2-3631-4"> <title>Oberons Legacy</title> <author>Corets, Eva</author> <price>5.95</price> </book> <book genre="update作者" ISBN="2-3631-4"> <title>CSS從入門到精通</title> <author>亞勝</author> <price>58.3</price> </book> </bookstore> |