在C#中移除XML节点:保留指定文件节点并删除其余节点
Filter XML Nodes to Match File Path List
Got it, here's a straightforward way to keep only the <filesource> nodes that correspond to paths in your filenames list, and delete all others. The critical thing to avoid is modifying the node collection while iterating over it—so we'll first gather all the nodes that need removing, then delete them in a separate loop.
Step-by-Step Code Solution
// Get the parent <files> node (fixed typo from findNode to SelectSingleNode) XmlNode filesNode = xmlFile.SelectSingleNode("/root/files"); if (filesNode == null) { // Handle scenario where <files> node doesn't exist in the XML return; } // Convert your list to a HashSet for faster lookups (O(1) vs O(n) with List) // Use StringComparer.OrdinalIgnoreCase if you want case-insensitive path matches (Windows-friendly) HashSet<string> pathsToKeep = new HashSet<string>(filenames, StringComparer.OrdinalIgnoreCase); // Collect all <filesource> nodes that don't match our keep list List<XmlNode> nodesToRemove = new List<XmlNode>(); foreach (XmlNode childNode in filesNode.ChildNodes) { if (childNode.Name.Equals("filesource", StringComparison.Ordinal)) { string nodeFilePath = childNode.InnerText.Trim(); // Trim whitespace just in case if (!pathsToKeep.Contains(nodeFilePath)) { nodesToRemove.Add(childNode); } } } // Remove the unwanted nodes from the parent foreach (XmlNode nodeToDelete in nodesToRemove) { filesNode.RemoveChild(nodeToDelete); }
Key Notes:
- HashSet for Performance: If your
filenameslist is large, using aHashSetinstead of aListfor lookups will make the code much faster—checking membership in a HashSet is constant time, whereasList.Contains()is linear. - Avoid Collection Modification During Iteration: Directly removing nodes while looping through
filesNode.ChildNodeswill throw an exception because the collection is being modified mid-iteration. Collecting nodes to remove first avoids this issue. - Path Escaping: Make sure your
filenameslist uses properly escaped paths in C#. Either use verbatim strings like@"c:\uploadDir\..."or double backslashesc:\\uploadDir\\...to prevent escape character issues. - Case Insensitivity: The
StringComparer.OrdinalIgnoreCaseparameter makes the path matches case-insensitive, which is ideal for Windows systems where file paths aren't case-sensitive. Remove this if you need exact case matching.
内容的提问来源于stack exchange,提问作者darma
相关产品推荐
相关产品推荐

