XML样例:
<?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> <book genre="李3" ISBN="2-3631-4"> <title>CS从入门到精通</title> <author>候捷</author> <price>58.3</price> </book> </bookstore>执行代码一:
/// <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); XmlNodeList xNodes = xmlDoc.SelectSingleNode(xpath).ChildNodes; for (int i = xNodes.Count - 1; i >= 0; 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> </bookstore>小注:
1、删除节点不能使用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);
}