Skip to content

Instantly share code, notes, and snippets.

@stevencohn
Created December 22, 2020 13:40
Show Gist options
  • Save stevencohn/ab3ff9cd7c02c464395117dc80931909 to your computer and use it in GitHub Desktop.
Save stevencohn/ab3ff9cd7c02c464395117dc80931909 to your computer and use it in GitHub Desktop.
Prune XML hierarchy branches that do not contain specific element
// 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