Created
December 22, 2020 13:40
-
-
Save stevencohn/ab3ff9cd7c02c464395117dc80931909 to your computer and use it in GitHub Desktop.
Prune XML hierarchy branches that do not contain specific element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given an XElement, remove all leaf nodes that do NOT contain a specific node. | |
// Also removes ancestor branches that do not result in the specific leaf node. | |
// Useful for pruning hierarchies, such as a disk directory structure that only shows | |
// directory paths that contain files | |
void Prune(XElement element) | |
{ | |
if (element.Elements().Any(e => e.Name.LocalName == "Page")) | |
{ | |
return; | |
} | |
if (element.HasElements) | |
{ | |
foreach (var item in element.Elements().ToList()) | |
{ | |
Prune(item); | |
} | |
if (!element.HasElements) | |
element.Remove(); | |
} | |
else | |
{ | |
element.Remove(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment