[英]Can I declare and fill an array from an XML document without looping?
I 'd like to fill a new string array with elements from an XML document. 我想用XML文档中的元素填充新的字符串数组。
In VBA I've managed this logic with a collection: 在VBA中,我使用集合来管理此逻辑:
For Each x In xmlDoc.SelectNodes("//a")
MyCollection.add (x.Attributes.getNamedItem("href").Text)
Next x
But what I really want to do is get the same collection in to an array in C#, something like: 但是我真正想做的是将相同的集合放入C#的数组中,例如:
string[] MyArray = new string[]
{
xmlDoc.SelectNodes("//a").Attributes.getNamedItem("href").Text
};
Is this possible? 这可能吗? Or some similar way to do it without looping and adding individually to the array? 还是一些类似的方法可以做到这一点而无需循环并单独添加到数组中?
This will do 这会做
string[] MyArray = XDocument.Parse(xml).XPathSelectElements("//a").Select(e => e.Attributes("href").FirstOrDefault().Value).ToArray()`
Edit: Requires Using System.Xml.XPath
and Using System.XML.Linq
to work 编辑:需要Using System.Xml.XPath
和Using System.XML.Linq
才能工作
You can use LINQ to achieve something like that: 您可以使用LINQ来实现以下目的:
string[] MyArray = xmlDoc
.SelectNodes("//a")
.Cast<XmlNode>()
.Select(e => e.Attributes.GetNamedItem("href").InnerText)
.ToArray();
Don't forget to import Linq ( using System.Linq;
) 别忘了导入Linq( using System.Linq;
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.