如何从XmlDocument创建XmlElement [] [英] how to create XmlElement[] from XmlDocument
本文介绍了如何从XmlDocument创建XmlElement []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何正文都可以帮我找出如何在C#中获取XmlElement []数组中XmlDocument的所有元素。
谢谢
解决方案
您将很好地学习如何指定Xml 位置路径 [ ^ ]用于SelectNodes方法。
此示例将返回文档中所有XmlElements的XMLNodeList。
XmlDocument doc = new XmlDocument();
doc.LoadXml(test1.xml);
XmlNodeList nodes = doc.DocumentElement.SelectNodes(// *);
如果你必须有一个数组,然后:XmlElement [] elementarray = nodes.Cast< XmlElement>()。ToArray();
你可以尝试递归每个XmlElement
的孩子。
这样的东西可以帮到你;
类程序{
静态IEnumerable < XmlElement > Recurse(XmlElement元素){
yield return element;
foreach(element.OfType中的var childElement < XmlElement > ()。选择(Recurse).SelectMany(childElements => childElements)){
yield return childElement;
}
}
static void Main(string [] args){
var document = new XmlDocument();
document.LoadXml(< Root > < 儿童 > < 数据 > 1C < / Data > < span class =code-keyword>< / Child > < 子 > < 数据 > 2C < / Data > < / Child > < span class =code-keyword>< / Root > );
var array = document.Cast < XmlElement > 跨度>()的SelectMany(递归).ToArray();
foreach(数组中的var节点){
Console.WriteLine(node.Name);
}
}
}
希望这有帮助,
Fredrik
你好,
你可以使用LINQ to XML是完美而简单的方法。
http://msdn.microsoft.com/en -us / library / bb387098.aspx [ ^ ]
can any body help me to find out that how to fetch all elements of a XmlDocument in XmlElement[] array in C#
thanks
解决方案
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();
You could try recursing over the children of eachXmlElement
.
Something like this might do the trick for you;
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
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[^]
这篇关于如何从XmlDocument创建XmlElement []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文