【发布时间】:2008-10-02 20:12:20
【问题描述】:
任何像 /NodeName/position() 这样的 XPath 都会为您提供节点的位置 w.r.t 它是父节点。
XElement (Linq to XML) 对象上没有可以获取元素位置的方法。有吗?
【问题讨论】:
标签: linq linq-to-xml
任何像 /NodeName/position() 这样的 XPath 都会为您提供节点的位置 w.r.t 它是父节点。
XElement (Linq to XML) 对象上没有可以获取元素位置的方法。有吗?
【问题讨论】:
标签: linq linq-to-xml
实际上 NodesBeforeSelf().Count 不起作用,因为它甚至可以获取 XText 类型的所有内容
问题是关于 XElement 对象。 所以我认为是
int position = obj.ElementsBeforeSelf().Count();
应该使用,
感谢科比的指导。
【讨论】:
您可以使用 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()。 :)
【讨论】:
static int Position(this XNode node) {
var position = 0;
foreach(var n in node.Parent.Nodes()) {
if(n == node) {
return position;
}
position++;
}
return -1;
}
【讨论】:
其实在XDocument的Load方法中可以设置SetLineInfo的加载选项,然后可以将XElements类型转换为IXMLLineInfo来获取行号。
你可以做类似的事情
var list = from xe in xmldoc.Descendants("SomeElem")
let info = (IXmlLineInfo)xe
select new
{
LineNum = info.LineNumber,
Element = xe
}
【讨论】: