C#中XML遍历新增节点及修改属性的例子2014-10-01XML样例:
<?xml version="1.0" encoding="gb2312"?><bookstore><book genre="李2红" ISBN="2-3631-4"><title>CS从入门到精通</title><author>候捷</author><price>58.3</price></book><book genre="李赞红" ISBN="2-3631-4"><title>CS从入门到精通</title><author>小六</author><price>58.3</price></book><book45 genre="李赞红" ISBN="2-3631-4"><title>CS从入门到精通</title><author>大黄</author><price>58.3</price></book45></bookstore>
测试代码:
<span style="white-space:pre"></span>XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("E:\bookstore.xml");//获取bookstore节点的所有子节点// 查看本栏目更多精彩内容:http://www.bianceng.cn/Programming/csharp/XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;for (int i = 0; i < nodeList.Count; i++)//遍历每个book节点{ //将子节点类型转换为XmlElement类型XmlElement xe = (XmlElement)nodeList.Item(i);if (xe.Name == "book"){ //如果genre属性值为“李赞红”if (xe.GetAttribute("genre") == "李赞红"){//继续获取xe子节点的所有子节点XmlNodeList nls = xe.ChildNodes;for (int j = 0; j < nls.Count; j++){XmlElement xe2 = (XmlElement)nls.Item(j);//转换类型//title、author、price都会在xe2.Name中取到if (xe2.Name == "author")//如果找到{xe2.InnerText = "Karli Waston";//则修改}else //如果不存在则新建{xe2.SetAttribute("NewAttribute", "新增属性");}}}else{//如果genre属性值不为“李赞红”,则修改为李赞红xe.SetAttribute("genre", "李赞红");}}else //如果不存在book节点,则在该节点下新增一个book下级节点{XmlElement subElement = xmlDoc.CreateElement("因为这个节点不是book");subElement.InnerXml = "BigDog";xe.AppendChild(subElement);}}xmlDoc.Save("E:\bookstore.xml");//保存。
修改后的XML:
<?xml version="1.0" encoding="gb2312"?><bookstore><book genre="李赞红" ISBN="2-3631-4"><title>CS从入门到精通</title><author>候捷</author><price>58.3</price></book><book genre="李赞红" ISBN="2-3631-4"><title NewAttribute="新增属性">CS从入门到精通</title><author>Karli Waston</author><price NewAttribute="新增属性">58.3</price></book><book45 genre="李赞红" ISBN="2-3631-4"><title>CS从入门到精通</title><author>大黄</author><price>58.3</price><因为这个节点不是book>BigDog</因为这个节点不是book></book45></bookstore>
如果现在根节点下新增某个节点,代码如下:
XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("E:\bookstore.xml");XmlNode root = xmlDoc.DocumentElement;XmlElement subElement = xmlDoc.CreateElement("根节点下新增");subElement.InnerXml = "BigDog";root.AppendChild(subElement);