get xelement attribute value

LFurness picture LFurness · Jul 22, 2013 · Viewed 64.8k times · Source

I have an XElement that looks like this:

<User ID="11" Name="Juan Diaz" LoginName="DN1\jdiaz" xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/" />

How can I use XML to extract the value of the LoginName attribute? I tried the following, but the q2 "Enumeration yielded no results".

var q2 = from node in el.Descendants("User")
    let loginName = node.Attribute(ns + "LoginName")
    select new { LoginName = (loginName != null) };
foreach (var node in q2)
{
    Console.WriteLine("LoginName={0}", node.LoginName);
}

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Jul 22, 2013
var xml = @"<User ID=""11"" 
                  Name=""Juan Diaz"" 
                  LoginName=""DN1\jdiaz"" 
                  xmlns=""http://schemas.microsoft.com/sharepoint/soap/directory/"" />";

var user = XElement.Parse(xml);
var login = user.Attribute("LoginName").Value; // "DN1\jdiaz"