Find XML Element Index - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Find XML Element Index

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.IO;/*from  w  w  w .j av  a 2  s .  co  m*/
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        static int FindElementIndex(XmlElement element)
        {
            XmlNode parentNode = element.ParentNode;
            if( parentNode is XmlDocument )
            {
                return 1;
            }
            XmlElement parent = (XmlElement)parentNode;
            int index = 1;
            foreach( XmlNode candidate in parent.ChildNodes )
            {
                if( candidate is XmlElement && candidate.Name == element.Name )
                {
                    if( candidate == element )
                        return index;

                    index++;
                }
            }
            throw new ArgumentException( "Couldn't find element within parent" );
        }
}

Related Tutorials