2013-05-08 1 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); 

Чтобы закончить с этим.

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

Создание узла и вставка его в индекс, у меня нет проблем. Просто нужен способ получить индекс.

ответ

1

Для полноты, это то же самое, как ответ Натана выше, только используя анонимный класс вместо кортежей:

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