在工作中遇到,多人协作开发时,合并文件后会导致同一个文件在csproject中重复注册,故写一个小Demo进行清理
删除方法主体:用的是最简单的临时表去判断是否重复
public static void ClearXmlNode(string XPath,string NodeName,string NodeAttribute)
{
XmlDocument doc = new XmlDocument();
doc.Load(XPath);
XmlNodeList elemList = doc.GetElementsByTagName(NodeName);
List<string> templist = new List<string>();
int oldconut = elemList.Count;
for (int i = 0; i < elemList.Count; i++)
{
XmlNode item = elemList[i];
string temp = item.Attributes[NodeAttribute].Value.ToString();
if (templist.FindIndex(t => t == temp) == -1)
{
templist.Add(temp);
}
else
{
Console.WriteLine("删除节点:" + temp);
//删除后游标向前移动一格
i--;
item.ParentNode.RemoveChild(item);
}
}
//Console.WriteLine("节点总数:" + oldconut);
//Console.WriteLine("清理后节点总数:" + elemList.Count);
//Console.WriteLine("临时表节点数量" + templist.Count);
doc.Save(XPath);
}
使用:
static void Main(string[] args)
{
ClearXmlNode("F:/Demo/ClearCsproj/ClearCsproj/App_Data/demo.xml", "Compile", "Include");
ClearXmlNode("F:/Demo/ClearCsproj/ClearCsproj/App_Data/demo.xml", "Content", "Include");
}