Convert XmlNodeList to XmlNode[]

25,511

Solution 1

Try this (VS2008 and target framework == 2.0):

static void Main(string[] args)
{
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml("<a><b /><b /><b /></a>");
    XmlNodeList xmlNodeList = xmldoc.SelectNodes("//b");
    XmlNode[] array = (
        new System.Collections.Generic.List<XmlNode>(
            Shim<XmlNode>(xmlNodeList))).ToArray();
}

public static IEnumerable<T> Shim<T>(System.Collections.IEnumerable enumerable)
{
    foreach (object current in enumerable)
    {
        yield return (T)current;
    }
}

Hints from here: IEnumerable and IEnumerable(Of T) 2

Solution 2

How about this straightfoward way...

var list = new List<XmlNode>(xml.DocumentElement.GetElementsByTagName("nodeName").OfType<XmlNode>());
var itemArray = list.ToArray();

No need for extension methods etc...

Solution 3

 XmlNode[] nodeArray = myXmlNodeList.Cast<XmlNode>().ToArray();
Share:
25,511
GrayWizardx
Author by

GrayWizardx

http://twitter.com/graywizardx/ Just your average developer

Updated on July 09, 2022

Comments

  • GrayWizardx
    GrayWizardx almost 2 years

    I have a external library that requires a "XmlNode[]" instead of XmlNodeList. Is there a direct way to do this without iterating over and transferring each node?

    I dont want to do this:

    XmlNode[] exportNodes = XmlNode[myNodeList.Count];
    int i = 0;
    foreach(XmlNode someNode in myNodeList) { exportNodes[i++] = someNode; }
    

    I am doing this in .NET 2.0 so I need a solution without linq.

  • vcsjones
    vcsjones over 12 years
    OfType is a LINQ extension.
  • Rubens Farias
    Rubens Farias almost 8 years
    @CaTx OP asked for a solution without Linq, and other answers use it. The Shim method is offered as an extension method, so it can be reused and placed in another class with other extensions methods. If you have different requirements, you should ask a new question.