如何在没有相应属性名称的情况下检索 XML 属性的值?

How to retrieve the values of XML Attributes without the names of the respective attribute?

我正在使用 XDocument 和 C#。

我有以下 XML-数据,我想从中提取 ID(c5946、cdb9fb 等):

<rootElement>
    <IDs>
       <ID value="c5946"/>
       <ID value="cdb9fb"/>
       <ID value="c677f5"/>
       <ID value="ccc78b"/>
   </IDs>
</rootElement>

我尝试了不同的东西,其中包括:

XDocument xDoc = XDocument.Load(filename);
var Ids = xDoc.Root.Element("IDs").Elements("ID").Attributes("value");

但是这个returns:

 value="c5946", value="cdb9fb", etc.

而不是

c5946, cdb9fb, etc.

如何在没有相应属性名称的情况下获取属性值?

使用 .Value 属性 属性

var allId = document.Descendants("ID").Select(id => id.Attribute("value").Value);

或者您可以将 XAttribute 转换为 string

var allId = document.Descendants("ID").Select(id => (string)id.Attribute("value"));

如果元素中不存在属性,转换将是更简单的方法。

var allId = document.Descendants("ID").Select(id => (string)id.Attribute("value") ?? "");