Question

The situation: I have an XML file (mostly lots of Boolean logic). What I would like to do: Get the index of a node by the inner-text of an attribute in that node. To then add childnodes to the given index.

Example:

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

I can get an index list of a given element name

GetElementsByTagName("if");

But how would I get the index of the node in the node list, by using the innertext of the attribute.

Basicly thinking of something along the lines of

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

To end up with this.

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

Creating the node and inserting it at an index, I have no problem. Just need a way to get the index.

Was it helpful?

Solution 2

For completeness, this is the same as Nathan's answer above, only using an anonymous class instead of a Tuple:

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

OTHER TIPS

The linq select function has an override which provides the current index:

            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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top