任何类似于 /NodeName/position() 的 XPath 表达式都可以给出节点相对于其父节点的位置。
在 XElement(Linq to XML)对象上没有可以获取元素位置的方法。有吗?
在 XElement(Linq to XML)对象上没有可以获取元素位置的方法。有吗?
实际上,NodesBeforeSelf().Count 不起作用,因为它获取的是所有类型为 XText 的元素。
问题是关于 XElement 对象的。所以我猜想这是
int position = obj.ElementsBeforeSelf().Count();
应该使用的内容,
感谢Bryant提供的指导。
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();
}
}
实际上,在XDocument的Load方法中,您可以设置SetLineInfo的加载选项,然后将XElements强制转换为IXMLLineInfo以获取行号。
您可以像这样执行操作
var list = from xe in xmldoc.Descendants("SomeElem")
let info = (IXmlLineInfo)xe
select new
{
LineNum = info.LineNumber,
Element = xe
}
static int Position(this XNode node) {
var position = 0;
foreach(var n in node.Parent.Nodes()) {
if(n == node) {
return position;
}
position++;
}
return -1;
}