12

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.

3
  • 1
    is there some reason not to iterate over the XmlNodeList and use it to load the XmlNode[]? Because if you'd done that, you'd be finished by now. Commented Dec 11, 2009 at 23:25
  • No reason, thats the current implementation. It just seems odd to my that it cant be done with more compiler semantics. Commented Dec 11, 2009 at 23:29
  • 2
    The compiler semantics for this are in the newer versions of C#/.NET :) If you're stuck with an older version, then you're stuck with what you've got. Commented Dec 11, 2009 at 23:48

3 Answers 3

20

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

Sign up to request clarification or add additional context in comments.

1 Comment

OfType is a LINQ extension.
14
 XmlNode[] nodeArray = myXmlNodeList.Cast<XmlNode>().ToArray();

Comments

8

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.