如何通过在XmlDocument或XDocument中传递xElement名称来获取绝对xpath?

时间:2012-02-06 15:13:35

标签: c# .net xml xpath linq-to-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)的absoulte xpath。 怎么做?

2 个答案:

答案 0 :(得分:4)

对于没有名称空间的简单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;
}

答案 1 :(得分:0)

我使用Descendants类的XDocument方法:

XElement xElement = xDocument.Descendants("Basic").First();

将XML元素“Basic”作为字符串传递给

public void ConvertObjectToXml(Employee employee )
{
    MemoryStream Stream = new MemoryStream();
    //To remove the default xml name space
    XmlSerializerNamespaces XmlNS = new XmlSerializerNamespaces();
    XmlNS.Add("", "");
    XmlSerializer XmlSerializer = new XmlSerializer(employee .GetType());
    XmlSerializer.Serialize(Stream, employee , XmlNS);
    Stream.Flush();
    Stream.Seek(0, SeekOrigin.Begin);
    XDocument xDocument = XDocument.Load(Stream);
    //Paasing the "Basic" as string
    XElement xElement = xDocument.Descendants("Basic").First();
    string xpath = GetPath(xElement);
      //Paasing the "Course" as string
    XElement XElement1 =xDocument.Descendants("Course").First();
    string xpath1 = GetPath(XElement1);
}

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)); 
        })); 
} 

public 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; 
}