C# 将 XmlNodeList 转换为 XmlNode[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1891521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:40:56  来源:igfitidea点击:

Convert XmlNodeList to XmlNode[]

c#xml.net-2.0

提问by GrayWizardx

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?

我有一个需要“XmlNode[]”而不是 XmlNodeList 的外部库。有没有直接的方法来做到这一点而无需迭代和传输每个节点?

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.

我在 .NET 2.0 中这样做,所以我需要一个没有 linq 的解决方案。

采纳答案by Rubens Farias

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

试试这个(VS2008 和目标框架 == 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

来自这里的提示:IEnumerable 和 IEnumerable(Of T) 2

回答by Rob

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

不需要扩展方法等...

回答by derloopkat

 XmlNode[] nodeArray = myXmlNodeList.Cast<XmlNode>().ToArray();