Get xml attribute values as string[]

。_饼干妹妹 提交于 2019-12-06 11:34:38

Assume let variable testXml is equal to the follow xml string

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

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 will contain {"if", "else", "is"}

UPDATE

Thanks to @SLaks comment, we could actually just do

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

You can make use of XmlNodeList class. You need to pass proper XPATH to fetch the values and iterate through the list.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!