如何获取XElement的position()?
时间:2020-03-06 15:02:51 来源:igfitidea点击:
像/ NodeName / position()这样的任何XPath都会为我们提供其父节点的节点位置。
XElement(Linq to XML)对象上没有任何方法可以获取Element的位置。在那儿?
解决方案
static int Position(this XNode node) {
var position = 0;
foreach(var n in node.Parent.Nodes()) {
if(n == node) {
return position;
}
position++;
}
return -1;
}
我们可以使用NodesBeforeSelf方法来执行此操作:
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()。 :)
实际上NodesBeforeSelf()。Count不起作用,因为它甚至可以获取XText类型的所有内容
问题是关于XElement对象。
所以我想是
int position = obj.ElementsBeforeSelf().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
}

