简体   繁体   中英

get the ancestor nodes of a selected xml node using c# into a multiline text box

Im using c#.net. I have an xml file that contains many nodes. I have got the xml file into a tree view. Now when I select a particular node in the treeview, I should be able to display all its ancestors in a multiline text box. Please suggest me to do this job.

I´m not really sure what you want but this might be some thing to start with.
The extension method will get the xpath to an XElement node with attributes to specify the exact element more precisely.

public static string ToXPath(this XElement element)
{
    var current = element.Parent;
    string result = "";
    while (current != null)
    {
        string currentDef = current.Name.ToString();
        string attribsDef = "";
        foreach (var attrib in current.Attributes())
        {
            attribsDef += " and @" + attrib.Name + "='" + attrib.Value + "'";
        }
        if (attribsDef.Length > 0)
        {
            currentDef += "[" + attribsDef.Substring(5) + "]";
        }
        result = "/" + currentDef + result;
        current = current.Parent;
    }
    return result.Substring(1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM