2008-10-02 44 views
5

像/节点名/位置任意的XPath()将w.r.t它的父节点给你节点的位置。如何获取XElement的位置()?

上有没有的XElement方法(LINQ到XML)对象,该对象可以得到元件的位置。在那儿?

回答

9

其实NodesBeforeSelf()。计数不工作,因为它甚至得到的一切类型的XTEXT

问题是关于的XElement对象。 所以我想这是

应使用
int position = obj.ElementsBeforeSelf().Count(); 

感谢科比的方向。

0
static int Position(this XNode node) { 
    var position = 0; 
    foreach(var n in node.Parent.Nodes()) { 
    if(n == node) { 
     return position; 
    } 
    position++; 
    } 
    return -1; 
} 
5

你可以使用NodesBeforeSelf方法来做到这一点:

XElement root = new XElement("root", 
     new XElement("one", 
      new XElement("oneA"), 
      new XElement("oneB") 
     ), 
     new XElement("two"), 
     new XElement("three") 
    ); 

    foreach (XElement x in root.Elements()) 
    { 
     Console.WriteLine(x.Name); 
     Console.WriteLine(x.NodesBeforeSelf().Count()); 
    } 

更新:如果你真的只想要一个位置的方法,只需添加一个扩展方法。

public static class ExMethods 
{ 
    public static int Position(this XNode node) 
    { 
     return node.NodesBeforeSelf().Count(); 
    } 
} 

现在你可以调用x.Position()。 :)

+0

感谢,x.NodesBeforeSelf()。COUNT()简单的作品,伟大的。 希望他们在XElement课堂上将它称为位置。 – Vin 2008-10-02 20:47:54

+0

推翻我以前的评论。在下面检查我的答案。 – Vin 2008-10-07 15:40:34

0

其实在的XDocument的Load方法,你可以设置SetLineInfo的加载选项,您可以强制转换XElements到IXMLLineInfo获得的行号。

你可以做类似

var list = from xe in xmldoc.Descendants("SomeElem") 
      let info = (IXmlLineInfo)xe 
      select new 
      { 
       LineNum = info.LineNumber, 
       Element = xe 
      }