gpt4 book ai didi

c# - 使用 LINQ 查找具有特定属性名称和值的 XElement

转载 作者:可可西里 更新时间:2023-11-01 08:00:29 26 4
gpt4 key购买 nike

XDocument xDocument = XDocument.Load("...");
IEnumerable<XElement> elements = xDocument
.Element("lfm")
.Element("events")
.Elements("event");

try
{
foreach (XElement elm in elements)
{
comm.Parameters.AddWithValue("extID", elm.Element("id").Value ?? "");
comm.Parameters.AddWithValue("Title", elm.Element("title").Value ?? "");
comm.Parameters.AddWithValue("HeadlineArtist",
elm.Element("artists").Element("headliner").Value ?? "");

但我想要属性为“size=large”的元素“image”的值,我整夜都在寻找,这是我最接近的:

comm.Parameters.AddWithValue("LargeImage",
elm.Descendants("image")
.FirstOrDefault(i => (string)i.Attribute("size") == "large").Value);

XML响应部分示例:

<lfm status="ok">
<events xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
location="Chicago, United States" page="1" perPage="1"
totalPages="341" total="341" festivalsonly="0" tag="">
<event xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<id>3264699</id>
<title>Iron And Wine</title>
<artists>
<artist>Iron And Wine</artist>
<artist>Dr. John</artist>
<headliner>Iron And Wine</headliner>
</artists>
<venue>
<id>8915382</id>
<name>Ravinia Festival</name>
<location>
<city>Highland Park</city>
<country>United States</country>
<street>200 Ravinia Park Rd</street>
<postalcode>60035</postalcode>
<geo:point>
<geo:lat>42.15831</geo:lat>
<geo:long>-87.778409</geo:long>
</geo:point>
</location>
<url>http://www.last.fm/venue/8915382+Ravinia+Festival</url>
<website>http://www.ravinia.org/</website>
<phonenumber>847.266.5100</phonenumber>
<image size="small">http://userserve-ak.last.fm/serve/34/63026487.jpg</image>
<image size="medium">http://userserve-ak.last.fm/serve/64/63026487.jpg</image>
<image size="large">http://userserve-ak.last.fm/serve/126/63026487.jpg</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/252/63026487.jpg</image>

最佳答案

尝试

XElement result = elm.Descendants("image")
.FirstOrDefault(el => el.Attribute("size") != null &&
el.Attribute("size").Value == "large");
if (result != null) {
process result.Value ...
}

从 C#6.0 (VS 2015) 开始,您可以编写:

XElement result = elm.Descendants("image")
.FirstOrDefault(el => el.Attribute("size")?.Value == "large");
if (result != null) {
process result.Value ...
}

一个不明显的替代方案(如@RandRandom 指出的那样)是将属性转换为 string:

XElement result = elm.Descendants("image")
.FirstOrDefault(el => (string)el.Attribute("size") == "large");
if (result != null) {
process result.Value ...
}

这行得通,因为 XAttribute Explicit Conversion (XAttribute to String) .

关于c# - 使用 LINQ 查找具有特定属性名称和值的 XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10982167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com