문제

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.

도움이 되었습니까?

해결책 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);
        }
    }
}

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top