1

Given the following XML file:

<users>
  <user name="admin" password="foobar" roles="Admin,Guest" />
  <user name="guest" password="foobar" roles="Guest" />
</users>

How do I find a specific node? In this case I want to find the node that has its name attribute to be "admin"

    Dim authGroup As XElement = XElement.Parse(myXMLDoc.OuterXml)
    Dim foundUser As IEnumerable(Of XElement) = From i In authGroup.Elements Where i.Attributes("name") = "admin" Select i

    'How can I determine if the user was found?
    Dim p As String =  ...... (get the password from foundUser)

2 Answers 2

2
Dim doc As XElement =
    <users>
        <user name="admin" password="foobar" roles="Admin,Guest" />
        <user name="guest" password="foobar" roles="Guest" />
    </users>
Dim userName = "admin"

Dim result =
    doc.Descendants("user")                                                    _
       .Where(Function(user) CType(user.Attribute("name"), String) = userName) _
       .SingleOrDefault

If result IsNot Nothing Then
    ' user found '
    Dim pw = CType(result.Attribute("password"), String)
    ' do something with pw '
End If
Sign up to request clarification or add additional context in comments.

2 Comments

What type is "doc"? The Descendants function is not being found.
It should come back as an XElement as that is an XML literal (without the declaration)
2
Dim root As XElement = XElement.Load("users.xml")
Dim admin As XElement = root.Elements().FirstOrDefault(Function(u) u.Attribute("name").Value = "admin")
If admin IsNot Nothing Then
    Dim password As String = admin.Attribute("password").Value
End If

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.