2012-03-02 124 views
1

查詢XML與LINQ考慮下面的XML文件:通過屬性

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

如何找到特定的節點?在這種情況下,我想找到一個具有其name屬性爲「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
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 
+0

什麼類型爲「DOC」的節點?後代功能未找到。 – WhiskerBiscuit 2012-03-02 14:40:46

+0

它應該以'XElement'的形式返回,因爲它是一個XML文字(沒有聲明) – 2012-03-02 14:42:17

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