且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取 xml 属性值作为 string[]

更新时间:2023-11-14 15:36:22

假设让变量testXml等于后面的xml字符串

Assume let variable testXml is equal to the follow xml string

<Keywords>
 <Keyword name = "if" />
 <Keyword name = "else" />
 <Keyword name = "is" />
</Keywords>

使用 XElement 和 LINQ 提取名称属性值

Use XElement and LINQ to extract the name attribute values

var myXml = XElement.Parse(testXml );
var myArray = myXml.Elements().Where(n => n.Name.LocalName.Equals("Keyword"))
                    .Select(n => n.Attribute("name").Value)
                    .ToArray();

myArray 将包含 {"if", "else", "is"}

myArray will contain {"if", "else", "is"}

更新

感谢@SLaks 的评论,我们实际上可以做到

Thanks to @SLaks comment, we could actually just do

var myArray = myXml.Elements("Keyword").Attributes("name").Select(n => n.Value);