Search code examples
c#xmllinq-to-xmlxelement

get xelement attribute value


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);
}

Solution

  • 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"