How to get position () XElement?

Any XPath, such as / NodeName / position (), will give you the Node wrt it parent node position.

There is no method in an XElement (Linq to XML) object that can get the position of an element. There is?

+6
linq linq-to-xml
source share
4 answers

Actually NodesBeforeSelf (). Count does not work because it gets everything even from type XText

Question about the XElement object. Therefore, I realized that

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

which should be used

Thanks to Bryant for the referral.

+9
source share

You can use the NodesBeforeSelf method for 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 need the 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 (). :)

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

In fact, in the Load XDocument method, you can set the load parameter to SetLineInfo, then you can give XElements to IXMLLineInfo to get the line number.

you can do something like

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

All Articles