public static void distinct(string filePath) { //1、创建XML文档对象 XmlDocument doc = new XmlDocument(); //2、加载指定路径的XML doc.Load(filePath); //3、获得根节点 XmlElement root = doc.DocumentElement; //4-1、获得根节点的所有子节点 XmlNodeList allNodes = root.ChildNodes; for (int i = 0; i < allNodes.Count - 1; i++) { XmlElement node_Element = (XmlElement)allNodes[i]; string currentNodeValue = node_Element.GetAttribute("Include"); for (int j = i + 1; j < allNodes.Count; j++) { XmlElement node_Element_temp = (XmlElement)allNodes[j]; if (node_Element_temp.GetAttribute("Include") == currentNodeValue) { node_Element_temp.ParentNode.RemoveChild(node_Element_temp); j--; continue; } } } doc.Save(filePath); }
调用
string path = @"..\..\upload\demo.xml";
distinct(path);
<?xml version="1.0" encoding="utf-8"?> <ItemGroup> <Compile Include="1" /> <Compile Include="1" /> <Compile Include="1" /> <Compile Include="2" /> <Compile Include="3" /> <Compile Include="1" /> <Compile Include="1" /> </ItemGroup>