【问题标题】:Getting index of element by attribute value通过属性值获取元素的索引
【发布时间】:2013-05-08 08:48:20
【问题描述】:

情况:我有一个 XML 文件(大部分是布尔逻辑)。我想做的事: 通过该节点中属性的内部文本获取节点的索引。然后将子节点添加到给定的索引。

例子:

<if attribute="cat">
</if>
<if attribute="dog">
</if>
<if attribute="rabbit">
</if>

我可以获得给定元素名称的索引列表

GetElementsByTagName("if");

但是如何通过使用属性的内部文本来获取节点列表中节点的索引。

基本上是这样想的

Somecode.IndexOf.Attribute.Innertext("dog").Append(ChildNode);

到此结束。

<if attribute="cat">
</if>
<if attribute="dog">
    <if attribute="male">
    </if>
</if>
<if attribute="rabbit">
</if>

创建节点并将其插入索引,我没有问题。只需要一种获取索引的方法。

【问题讨论】:

    标签: c# xml xmlnodelist


    【解决方案1】:

    linq 选择函数有一个提供当前索引的覆盖:

                string xml = @"<doc><if attribute=""cat"">
    </if>
    <if attribute=""dog"">
    </if>
    <if attribute=""rabbit"">
    </if></doc>";
    
                XDocument d = XDocument.Parse(xml);
    
                var indexedElements = d.Descendants("if")
                        .Select((node, index) => new Tuple<int, XElement>(index, node)).ToArray()  // note: materialise here so that the index of the value we're searching for is relative to the other nodes
                        .Where(i => i.Item2.Attribute("attribute").Value == "dog");
    
    
                foreach (var e in indexedElements)
                    Console.WriteLine(e.Item1 + ": " + e.Item2.ToString());
    
                Console.ReadLine();
    

    【讨论】:

      【解决方案2】:

      为了完整起见,这与上面 Nathan 的回答相同,只是使用匿名类而不是元组:

      using System;
      using System.Linq;
      using System.Xml.Linq;
      
      namespace ConsoleApplication1
      {
          class Program
          {
              static void Main()
              {
                  string xml = "<root><if attribute=\"cat\"></if><if attribute=\"dog\"></if><if attribute=\"rabbit\"></if></root>";
                  XElement root = XElement.Parse(xml);
      
                  int result = root.Descendants("if")
                      .Select(((element, index) => new {Item = element, Index = index}))
                      .Where(item => item.Item.Attribute("attribute").Value == "dog")
                      .Select(item => item.Index)
                      .First();
      
                  Console.WriteLine(result);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2012-01-13
        • 1970-01-01
        • 1970-01-01
        • 2019-05-04
        相关资源
        最近更新 更多