Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XmlNodeList to XmlNode[]

Tags:

c#

xml

.net-2.0

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.

like image 382
GrayWizardx Avatar asked Dec 11 '09 23:12

GrayWizardx


People also ask

How to convert XmlNodeList to list in c#?

Select(id => library. GetMemberName(id)) . ToList(); Cast<XmlNode>() call is necessary, because XmlNodeList does not implement generic IEnumerable<T> , so you have to explicitly convert it to generic collection from non-generic IEnumerable .

What is XmlNodeList?

XmlNodeList supports iteration and indexed access. XmlNodeList is returned by the following properties and methods. XmlNode. ChildNodes - Returns an XmlNodeList containing all the children of the node. XmlNode.


3 Answers

 XmlNode[] nodeArray = myXmlNodeList.Cast<XmlNode>().ToArray();
like image 52
derloopkat Avatar answered Sep 29 '22 07:09

derloopkat


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...

like image 31
Rob Avatar answered Sep 29 '22 07:09

Rob


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

like image 27
Rubens Farias Avatar answered Sep 29 '22 08:09

Rubens Farias