zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 关于XML遍历新增节点,修改属性小例

c#属性遍历节点XML 修改 关于 新增
2023-09-14 09:03:15 时间
//获取bookstore节点的所有子节点 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 
如果现在根节点下新增某个节点,代码如下:


XmlNode root = xmlDoc.DocumentElement; XmlElement subElement = xmlDoc.CreateElement("根节点下新增"); subElement.InnerXml = "BigDog"; root.AppendChild(subElement);