我想用XML文档中的元素填充一个新的字符串数组。
在 VBA 中,我使用集合管理此逻辑:
For Each x In xmlDoc.SelectNodes("//a")
MyCollection.add (x.Attributes.getNamedItem("href").Text)
Next x
但我真正想做的是将相同的集合放入 C# 中的数组中,如下所示:
string[] MyArray = new string[]
{
xmlDoc.SelectNodes("//a").Attributes.getNamedItem("href").Text
};
这可能吗?或者一些类似的方法可以在不循环和单独添加到数组的情况下做到这一点?
这将可以
string[] MyArray = XDocument.Parse(xml).XPathSelectElements("//a").Select(e => e.Attributes("href").FirstOrDefault().Value).ToArray()`
编辑:需要Using System.Xml.XPath
和Using System.XML.Linq
才能工作
您可以使用 LINQ 实现如下目标:
string[] MyArray = xmlDoc
.SelectNodes("//a")
.Cast<XmlNode>()
.Select(e => e.Attributes.GetNamedItem("href").InnerText)
.ToArray();
不要忘记导入 Linq (using System.Linq;
(