user3516240 user3516240 - 17 days ago 5
Vb.net Question

How to use an XML File to store information VB

can someone show me an example of how to compare user input to the contents of the following XML File? I've been looking for a while but I cant find any examples that I understand properly.

<?xml version="1.0" encoding="UTF-8" ?>
<Users>
<User>
<id>1</id>
<firstName>Garry</firstName>
<userName>Domain\Garry</userName>
<hashedkey>Example1</hashedkey>
</User>
<User>
<id>2</id>
<firstName>Ben</firstName>
<userName>Domain\ben</userName>
<hashedkey>Example2</hashedkey>
</User>
</Users>


An example of what I want to do is:

If txtFirstName.text = XML.FirstName AND txtHashedkey.text = XML.hashedkey then
msgbox("Key matches"
else
msgbox("Key doesnt match"
end if


I obviously need to make sure the key matches for that particular user and not have the key in
<id>1</id>
match the key in
<id>2</id>
whilst the name is under
<id>1</id>
. Could someone please give me an example on how to do this?

Answer

Use LINQ to Xml

Dim givenFirstName As String = txtFirstName.Text
Dim givenHashedKey As String = txtHashedkey.Text

Dim doc As XDocument = XDocument.Load(pathToFile)
Dim result As XElement = 
    doc.Root.
        Elements("User").
        FirstOrDefault(Function(user)
                           return user.Element("firstName").Value.Equals(givenFirstName) AndAlso
                                  user.Element("hashedkey").Value.Equals(givenHashedKey)
                       End Function)

Where doc.Root is a root node ("Users").
Elements("User") return collection of all "User" xml nodes.
FirstOrDefault(lambda...) will execute our "check" expression and return first element where both firstName and hashedkey are equals to given values.

Edit:
If you need count of matching elements then use Count method with same predicate

Dim amountOfElements As Integer = 
    doc.Root.
        Elements("User").
        Count(Function(user)
                  return user.Element("firstName").Value.Equals(givenFirstName) AndAlso
                         user.Element("hashedkey").Value.Equals(givenHashedKey)
              End Function)