Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position() of an XElement?

Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node.

There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?

like image 906
Vin Avatar asked Oct 02 '08 20:10

Vin


3 Answers

Actually NodesBeforeSelf().Count doesn't work because it gets everything even of type XText

Question was about XElement object. So I figured it's

int position = obj.ElementsBeforeSelf().Count();

that should be used,

Thanks to Bryant for the direction.

like image 129
Vin Avatar answered Nov 16 '22 22:11

Vin


You could use the NodesBeforeSelf method to do this:

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

Update: If you really just want a Position method, just add an extension method.

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

Now you can just call x.Position(). :)

like image 39
Bryant Avatar answered Nov 16 '22 22:11

Bryant


Actually in the Load method of XDocument you can set a load option of SetLineInfo, you can then typecast XElements to IXMLLineInfo to get the line number.

you could do something like

var list = from xe in xmldoc.Descendants("SomeElem")
           let info = (IXmlLineInfo)xe
           select new 
           {
              LineNum = info.LineNumber,
              Element = xe
           }
like image 22
Tim Jarvis Avatar answered Nov 16 '22 23:11

Tim Jarvis