如何获得XElement的position()?

Vin*_*Vin 7 linq linq-to-xml

任何类似于/ NodeName/position()的XPath都会为您提供Node的位置,即它的父节点.

XElement(Linq to XML)对象上没有可以获取Element位置的方法.在那儿?

Vin*_*Vin 10

实际上NodesBeforeSelf().Count不起作用,因为它甚至可以获得XText类型的所有内容

问题是关于XElement对象.所以我认为是的

int position = obj.ElementsBeforeSelf().Count();
Run Code Online (Sandbox Code Playgroud)

应该使用,

感谢布莱恩特的指导.


Bry*_*ant 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()); 
    }
Run Code Online (Sandbox Code Playgroud)

更新:如果您真的只想要一个Position方法,只需添加一个扩展方法.

public static class ExMethods
{
    public static int Position(this XNode node)
    {
        return node.NodesBeforeSelf().Count();  
    }
}
Run Code Online (Sandbox Code Playgroud)

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