Click here to Skip to main content
15,886,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can any body help me to find out that how to fetch all elements of a XmlDocument in XmlElement[] array in C#

thanks
Posted

You would be well served to learn how to specify Xml location paths[^] for use in the SelectNodes method.

This example will return a XMLNodeList of all XmlElements in the document.

XmlDocument doc = new XmlDocument();
doc.LoadXml("test1.xml");
XmlNodeList nodes = doc.DocumentElement.SelectNodes("//*");


If you must have an Array, then: XmlElement[] elementarray = nodes.Cast<XmlElement>().ToArray();
 
Share this answer
 
You could try recursing over the children of each XmlElement.
Something like this might do the trick for you;

XML
class Program {
    static IEnumerable<XmlElement> Recurse(XmlElement element) {
        yield return element;

        foreach (var childElement in element.OfType<XmlElement>().Select(Recurse).SelectMany(childElements => childElements)) {
            yield return childElement;
        }
    }

    static void Main(string[] args) {
        var document = new XmlDocument();
        document.LoadXml("<Root><Child><Data>1C</Data></Child><Child><Data>2C</Data></Child></Root>");

        var array = document.Cast<XmlElement>().SelectMany(Recurse).ToArray();

        foreach (var node in array) {
            Console.WriteLine(node.Name);
        }
    }
}


Hope this helps,
Fredrik
 
Share this answer
 
hello man,

you can use LINQ to XML is the perfect and simple way to do this.

http://msdn.microsoft.com/en-us/library/bb387098.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900