我有一个这样的xml文件节点结构

<Employee>
    <EmpId></EmpId>
    <EmpName></EmpName>
    <Salary>
        <Basic></Basic>
        <HRA></HRA>
    </Salary>
    <Qualifications>
        <Course>
            <Name></Name>
            <Year></year>
        </course>
        <Course>
            <Name></Name>
            <Year></year>
        </course>
        <Course>
            <Name></Name>
            <Year></year>
        </course>
    </Qualifications>
<Employee>


从这个文件中,我想使用XmlDocument或XDocument获得任何给定元素名称(不是XElement)的绝对xpath。
怎么做?

最佳答案

对于没有名称空间的简单XML,请尝试以下操作:

public static string GetPath(XElement element)
{
    return string.Join("/", element.AncestorsAndSelf().Reverse()
        .Select(e =>
            {
                var index = GetIndex(e);

                if (index == 1)
                {
                    return e.Name.LocalName;
                }

                return string.Format("{0}[{1}]", e.Name.LocalName, GetIndex(e));
            }));

}

private static int GetIndex(XElement element)
{
    var i = 1;

    if (element.Parent == null)
    {
        return 1;
    }

    foreach (var e in element.Parent.Elements(element.Name.LocalName))
    {
        if (e == element)
        {
            break;
        }

        i++;
    }

    return i;
}

07-24 18:27
查看更多