如何在C#中通过LINQ获取xml中xml元素的属性名称 [英] How to get attribute names of element in xml by LINQ in C#
问题描述
我有xml元素:
<.SECTIONS>
<.SECTION ID ="1" NAME="System Health" CONTROL-TYPE="Button" LINK="http://www.google.co.in/">
<.DATAITEMS>
<./DATAITEMS>
<./SECTION>
<./SECTIONS>
I have xml element:
<.SECTIONS>
<.SECTION ID ="1" NAME="System Health" CONTROL-TYPE="Button" LINK="http://www.google.co.in/">
<.DATAITEMS>
<./DATAITEMS>
<./SECTION>
<./SECTIONS>
我想获取SECTION Element的所有属性名称.在服务器端使用LINQ to C#语言的XML作为ID,NAME,CONTROL-TYPE,LINK.我必须在那写什么查询?
I want to get the all attribute names of SECTION Element. as ID,NAME,CONTROL-TYPE,LINK at server side using LINQ to XML in C# language. What query I have to write there?
推荐答案
正如@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.
这篇关于如何在C#中通过LINQ获取xml中xml元素的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!