WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

Querying XML with LINQ by attribute

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)

Upvotes: 1

Views: 2752

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134601

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

Upvotes: 2

Meysam
Meysam

Reputation: 18177

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

Upvotes: 2

Related Questions