简体   繁体   中英

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. 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:

<?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. 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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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