2013-05-08 47 views
2

情況:我有一個XML文件(主要是大量的布爾邏輯)。我想要做什麼: 通過該節點中屬性的內部文本獲取節點的索引。然後將子節點添加到給定的索引。按屬性值獲取元素的索引

例子:

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

我可以得到一個給定的元素名稱

GetElementsByTagName("if"); 

的索引列表,但我將如何得到節點列表中的節點的索引,使用的innerText的屬性。沿

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

線條的東西

Basicly思維要這樣結束了。

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

創建節點並將它插入索引,我沒有問題。只需要一種方法來獲得索引。

回答

1

爲了完整性,這是相同的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); 
     } 
    } 
} 
2

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();