【问题标题】:How to get the position() of an XElement?如何获取 XElement 的位置()?
【发布时间】:2008-10-02 20:12:20
【问题描述】:

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

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

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

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

    问题是关于 XElement 对象。 所以我认为是

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

    应该使用,

    感谢科比的指导。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢,x.NodesBeforeSelf().Count() 很简单,很好。希望他们将其称为 XElement 类之上的位置。
      • 推翻我之前的评论。在下面检查我的答案。
      【解决方案3】:
      static int Position(this XNode node) {
        var position = 0;
        foreach(var n in node.Parent.Nodes()) {
          if(n == node) {
            return position;
          }
          position++;
        }
        return -1;
      }
      

      【讨论】:

        【解决方案4】:

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

        你可以做类似的事情

        var list = from xe in xmldoc.Descendants("SomeElem")
                   let info = (IXmlLineInfo)xe
                   select new 
                   {
                      LineNum = info.LineNumber,
                      Element = xe
                   }
        

        【讨论】:

        • 但这仍然不能为您提供相对于节点父节点的位置。不就是行号吗?
        猜你喜欢
        • 2015-11-22
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2010-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多