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

问题描述:

我在C#中使用了XDocument如何检索没有相应属性名称的XML属性的值?

我有下面的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"); 

但这返回:

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

,而不是

c5946, cdb9fb, etc. 

如何获取不带相应属性名称的属性值?

使用属性

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

.Value属性或特性不是当你可以投XAttributestring

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

铸件会更简单的办法的情况下,存在的元素。

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