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?
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.
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(). :)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With