8

任何像 /NodeName/position() 这样的 XPath 都会为您提供节点 wrt 的位置,它是父节点。

XElement(Linq to XML)对象上没有可以获取Element位置的方法。有没有?

4

4 回答 4

11

实际上 NodesBeforeSelf().Count 不起作用,因为它甚至可以获取 XText 类型的所有内容

问题是关于 XElement 对象。所以我想这是

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

应该使用的,

感谢科比的指导。

于 2008-10-02T23:19:52.920 回答
6

您可以使用 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()。:)

于 2008-10-02T20:36:16.213 回答
0
static int Position(this XNode node) {
  var position = 0;
  foreach(var n in node.Parent.Nodes()) {
    if(n == node) {
      return position;
    }
    position++;
  }
  return -1;
}
于 2008-10-02T20:33:25.707 回答
0

实际上,在 XDocument 的 Load 方法中,您可以设置 SetLineInfo 的加载选项,然后您可以将 XElements 类型转换为 IXMLLineInfo 以获取行号。

你可以做类似的事情

var list = from xe in xmldoc.Descendants("SomeElem")
           let info = (IXmlLineInfo)xe
           select new 
           {
              LineNum = info.LineNumber,
              Element = xe
           }
于 2008-10-02T23:36:39.947 回答