C# 从IEnumerable中读取特定元素<;XElement>;
我有一块XML:C# 从IEnumerable中读取特定元素<;XElement>;,c#,xml,linq,C#,Xml,Linq,我有一块XML: <Books> <BookData id="BookID_100"> <Name>The Catcher and the Rye</Name> <Description>This is a neat book that you might have had to read in school</Description> <Date>1/1/1900</Date&
<Books>
<BookData id="BookID_100">
<Name>The Catcher and the Rye</Name>
<Description>This is a neat book that you might have had to read in school</Description>
<Date>1/1/1900</Date>
<IsHardcover>1</IsHardcover>
</BookData>
<BookData id="BookID_101">
<Name>Harry Potter</Name>
<Description>J.K. Rowlings Fantasy Epic</Description>
<Date>1/1/2000</Date>
<IsHardcover>0</IsHardcover>
</BookData>
</Books>
您必须调用
Element
方法并传递要从XElement
获取的元素名称:
IEnumerable<XElement> book =
from el in root.Elements("BookData")
where el.Attribute("id").Value == "BookID_100"
select el.Element("Name");
您必须调用
Element
方法并传递要从XElement
获取的元素名称:
IEnumerable<XElement> book =
from el in root.Elements("BookData")
where el.Attribute("id").Value == "BookID_100"
select el.Element("Name");
当您显然只想要具有指定ID的书籍时,为什么要获取书籍元素的集合?如果您只想要一本书,可以使用
FirstOrDefault()
请尝试以下方法:
//This will return the first book matching: "BookID_100" or NULL
var book = root.Elements("BookData")
.FirstOrDefault(x => x.Attribute("id") == "BookID_100");
//'name' will be null if book or name is null, or the name of the book element
string name = book?.Element("Name")?.Value;
如果您未使用C#6或更高版本,则?。
运算符将不可用,在这种情况下,只需像往常一样检查null:
string name = string.Empty;
if(book != null && book.Element("Name") != null)
{
name = book.Element("Name").Value;
}
当您显然只想要具有指定ID的书籍时,为什么要获取书籍元素的集合?如果您只想要一本书,可以使用
FirstOrDefault()
请尝试以下方法:
//This will return the first book matching: "BookID_100" or NULL
var book = root.Elements("BookData")
.FirstOrDefault(x => x.Attribute("id") == "BookID_100");
//'name' will be null if book or name is null, or the name of the book element
string name = book?.Element("Name")?.Value;
如果您未使用C#6或更高版本,则?。
运算符将不可用,在这种情况下,只需像往常一样检查null:
string name = string.Empty;
if(book != null && book.Element("Name") != null)
{
name = book.Element("Name").Value;
}
对单个项目使用FirstOrDefault()
对单个项目使用FirstOrDefault()