ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FindParent(string parentName) - For XElement

Find parent XElement from a provided name. Returns null if no match

Source

public static XElement FindParent(this XElement e, string Name)
{
    XElement r = null;

    if (e == null)
        return r;
    
    if (e.Parent != null && e.Parent.Name == Name)
    {
        r = e.Parent;
    }
    else
    {
        r = e.Parent.FindParent(Name);
    }

    return r;
}

Example

XElement parentXElement = childXElement.FindParent("nodename");

Author: Andi Haviari

Submitted on: 31 mei 2016

Language: C#

Type: System.Xml.Linq.XElement

Views: 4345