C# Xml 移除指定节点
2023-09-14 09:03:15 时间
/// param name="xmlFileName" XML文档完全文件名(包含物理路径) /param
/// param name="xpath" 要匹配的XPath表达式(例如:"//节点名//子节点名 /param
/// param name="xmlAttributeName" 要删除包含xmlAttributeName属性的节点的名称 /param
/// param name="AttributeValue" /param
private void XmlNodeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string AttributeValue)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFileName);
XmlNodeList xNodes = xmlDoc.SelectSingleNode(xpath).ChildNodes;
for (int i = xNodes.Count - 1; i i--)
XmlElement xe = (XmlElement)xNodes[i];
if (xe.GetAttribute(xmlAttributeName) == AttributeValue)
xNodes[i].ParentNode.RemoveChild(xNodes[i]);
xmlDoc.Save(xmlFileName);
}
实验:XmlNodeByXPath("E:\\bookstore.xml", "bookstore", "genre", "李3");
?xml version="1.0" encoding="gb2312"? bookstore book genre="李1" ISBN="2-3645-4" title Net从入门到精通 /title author 李大蒜 /author price 58.3 /price /book book genre="李2" ISBN="2-3631-4" title CS从入门到精通 /title author 候捷 /author price 58.3 /price /book /bookstore1、删除节点不能使用foreach,使用的话会造成删除XML一个节点,就跳出循环,也不报错,很隐蔽的错误。 2、该函数也可以这么实现
/// summary /// 删除属性值等于“AttributeValue”的节点 /// /summary /// param name="xmlFileName" XML文档完全文件名(包含物理路径) /param /// param name="xpath" 要匹配的XPath表达式(例如:"//节点名//子节点名 /param /// param name="xmlAttributeName" 要删除包含xmlAttributeName属性的节点的名称 /param /// param name="AttributeValue" /param private void XmlNodeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string AttributeValue) XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFileName); XmlNode root = xmlDoc.SelectSingleNode(xpath); XmlNodeList xnl = xmlDoc.SelectSingleNode(xpath).ChildNodes; for (int i = 0; i xnl.Count; i++) XmlElement xe = (XmlElement)xnl.Item(i); if (xe.GetAttribute(xmlAttributeName) == AttributeValue) root.RemoveChild(xe); if (i xnl.Count) i = i - 1; xmlDoc.Save(xmlFileName); }
相关文章
- 【100个 Unity实用技能】| C# 中List 使用Exists方法判断是否存在符合条件的元素对象
- c#数组赋初值_C#数组初始化
- c#byte类型转换成string_java字符串转byte数组
- c# mysql executenonquery_C#与数据库访问技术总结(八)之ExecuteNonQuery方法
- C# 中List与json字符串的相互转换「建议收藏」
- C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑
- c#备忘录模式
- C#栈和堆的区别浅谈
- c#设置xml内容不换行及属性xsi:nil=true的空节点添加
- 浅谈C#2.0泛型中的变化:default关键字
- C#使用MailAddress类发送html格式邮件的实例代码
- C#四舍五入(函数)用法实例
- C#自动给文章关键字加链接实现代码
- C#使用Process类调用外部程序分解
- C#WinForm捕获未处理的异常实例解析