简体   繁体   English

C# - 检查从 XML 文件创建的列表中是否存在值

[英]C# - Checking if a value exists in a list created from an XML file

I have a small WinForm application that's a basic wallpaper scraper.我有一个小型的 WinForm 应用程序,它是一个基本的壁纸刮刀。 It has the ability for the user to 'blacklist' a wallpaper so it's never used again.它可以让用户将墙纸“列入黑名单”,使其不再使用。 When blacklisted, a wallpapers URL, title and ID are added into an XML file that's in the following format:列入黑名单后,壁纸 URL、标题和 ID 将添加到采用以下格式的 XML 文件中:

<?xml version="1.0" encoding="utf-8"?>
<!--This file stores a list of any wallpapers you blacklist.-->
<Blacklisted>
  <Wallpaper>
    <URL>http://i.imgur.com/OU3v9H6.jpg</URL>
    <Title>Gran Via Madrid Wallpaper [1920x1080]</Title>
    <ThreadID>54fsi7</ThreadID>
  </Wallpaper>
  <Wallpaper>
    <URL>http://i.imgur.com/TLXJmGB.jpg</URL>
    <Title>The Golden wallpaper HD [1920*1080]</Title>
    <ThreadID>55366b</ThreadID>
  </Wallpaper>
</Blacklisted>

When a new wallpaper is acquired, there is a quick check to see if the wallpaper URL is in the blacklisted XML file.获取新墙纸后,会快速检查墙纸 URL 是否在列入黑名单的 XML 文件中。 If it is, then it's not used and a new wallpaper is found.如果是,则未使用它并找到新墙纸。 My code for checking if the wallpaper is blacklisted is not actually causing any errors, however the rest of the code after the check is not executing so I believe there is something wrong with my checking process and the code is just getting 'stuck' .我用于检查墙纸是否被列入黑名单的代码实际上并没有导致任何错误,但是检查后的其余代码没有执行,所以我相信我的检查过程有问题,代码只是“卡住”了。 Here is my code for checking the XML file:这是我检查 XML 文件的代码:

string url = "http://example.url/image.jpg"            
XDocument xml = XDocument.Load("Blacklisted.xml");
var list = xml.Root.Elements("URL").Select(element => element.Value).ToList();

if(list.Contains(url))
{
    updateStatus("Wallpaper is blacklisted.");
    return;
}

It doesn't look like your list is being populated correctly.看起来您的列表没有正确填充。 Try using the Descendants method from your XDocument object.尝试使用 XDocument 对象中的 Descendants 方法。

var list = xml.Descendants("URL").Select(x=> x.Value).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM