Linq 如何获取XElement的位置()?
任何类似/NodeName/position()的XPath都会为您提供节点的位置,即它的父节点的位置Linq 如何获取XElement的位置()?,linq,linq-to-xml,Linq,Linq To Xml,任何类似/NodeName/position()的XPath都会为您提供节点的位置,即它的父节点的位置 XElement(Linq to XML)对象上没有可以获取元素位置的方法。有吗?您可以使用NodesBeforeSelf方法执行此操作: static int Position(this XNode node) { var position = 0; foreach(var n in node.Parent.Nodes()) { if(n == node) { r
XElement(Linq to XML)对象上没有可以获取元素位置的方法。有吗?您可以使用NodesBeforeSelf方法执行此操作:
static int Position(this XNode node) {
var position = 0;
foreach(var n in node.Parent.Nodes()) {
if(n == node) {
return position;
}
position++;
}
return -1;
}
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());
}
更新:如果您真的只需要一个Position方法,只需添加一个扩展方法
public static class ExMethods
{
public static int Position(this XNode node)
{
return node.NodesBeforeSelf().Count();
}
}
现在您可以调用x.Position()。:) 实际上nodesbeforeslf().Count不起作用,因为它甚至可以获取XText类型的所有内容
问题是关于这个物体。
所以我想是
int position = obj.ElementsBeforeSelf().Count();
应该用这个,
感谢Bryant的指导。实际上,在XDocument的加载方法中,您可以设置SetLineInfo的加载选项,然后可以将XElements键入IXMLLineInfo以获得行号 你可以这样做
var list = from xe in xmldoc.Descendants("SomeElem")
let info = (IXmlLineInfo)xe
select new
{
LineNum = info.LineNumber,
Element = xe
}
谢谢,x.nodesbeforeslf().Count()简单有效,太好了。但愿他们把它称为XElement类顶部的位置。驳回我之前的评论。检查我下面的答案。但这仍然不能给出节点相对于父节点的位置。这不只是电话号码吗?