按属性值获取元素索引

时间:2013-05-08 08:48:20

标签: c# xml xmlnodelist

情况:我有一个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>

创建节点并将其插入索引,我没有问题。只需要一种方法来获得索引。

2 个答案:

答案 0 :(得分:2)

linq select函数有一个覆盖,它提供当前索引:

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

答案 1 :(得分: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);
        }
    }
}
相关问题