使用LINQ by属性查询XML

时间:2012-03-02 14:08:16

标签: xml vb.net linq

给出以下XML文件:

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

如何找到特定节点?在这种情况下,我想找到名称属性为“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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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