I’ve been playing around with XML a little, trying to learn how it works, and ran into an odd problem. Sometimes, when I query my XML file, I don’t get results that I know exist. In fact, the only one I do get results for is the very first entry. The following is some example XML entries and a small function to see if a user exists.
<users>
<user>
<username>a</username>
<firstname>a</firstname>
<lastname>a</lastname>
</user>
<user>
<username>b</username>
<firstname>b</firstname>
<lastname>b</lastname>
</user>
<user>
<username>rawr</username>
<firstname>a</firstname>
<lastname>a</lastname>
</user>
</users>
>
private bool FindUser(string username)
{
XDocument doc = XDocument.Load(filePath);
var data = from item in doc.Descendants("users")
where item.Element("user").Element("username").Value == username.ToLower()
select new
{
usernameEle = item.Element("user").Element("username").Value
};
var p = data.FirstOrDefault();
if (p != null)
return true;
else
return false;
}
If I try to search for the user “a”, it returns true. If I do a search for any other username, it returns false.
I’m sure there is a simple solution but it is eluding me! Any help would be great.
I figured out the answer… but I’m not sure WHY this worked. I’m still somewhat new to XML…
I changed “item.Element(“user”).Element(“username”).Value” to “item.Element(“username”).Value”. Also changed “from item in doc.Descendants(“users”)” to “from item in doc.Descendants(“user”)”
to
It is now able to retrieve more than just the first entry. If I search b, or rawr, I get the appropriate results.
Odd.