Search code examples
c#xmlxmlnodelist

Getting index of element by attribute value


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.


Solution

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