且构网

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

如何在C#中通过LINQ获取xml中xml元素的属性名称

更新时间:2023-11-24 14:32:40

正如@Giu所提到的,您的XML在技术上是格式错误的.每个元素名称之前.

As @Giu mentions, your XML is technically malformed with the . preceding each element name.

要获取SECTION中可用属性的名称:

string xmlData = "<SECTIONS> <SECTION ID =\"1\" NAME=\"System Health\" CONTROL-TYPE=\"Button\" LINK=\"http://www.google.co.in/\"> <DATAITEMS> </DATAITEMS> </SECTION> </SECTIONS>";
XDocument doc = XDocument.Parse( xmlData );
//The above line could also be XDocument.Load( fileName ) if you wanted a file

IEnumerable<string> strings = doc.Descendants("SECTIONS")
                                 .Descendants("SECTION")
                                 .Attributes()
                                 .Select( a => a.Name.LocalName );

这将为您提供一个包含ID,NAME,CONTROL-TYPE和LINK的枚举.

This will give you an enumerable containing ID, NAME, CONTROL-TYPE, and LINK.

但是,如果您想要包含它们中的值,我会使用@Giu的答案.

However, if you want the values contained in them, I would use @Giu's answer.