Question

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);
}
Was it helpful?

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"

OTHER TIPS

XmlDocument doc = new XmlDocument();
doc.Load("myFile.xml"); //load your xml file
XmlNode user = doc.getElementByTagName("User"); //find node by tag name  
string login = user.Attributes["LoginName"] != null ? user.Attributes["LoginName"].Value : "unknown login";

The last line of code, where it's setting the string login, the format looks like this...

var variable = condition ? A : B;

It's basically saying that if condition is true, variable equals A, otherwise variable equals B.

from the docs for XAttribute.Value:

If you are getting the value and the attribute might not exist, it is more convenient to use the explicit conversion operators, and assign the attribute to a nullable type such as string or Nullable<T> of Int32. If the attribute does not exist, then the nullable type is set to null.

I ended up using string manipulation to get the value, so I'll post that code, but I would still like to see an XML approach if there is one.

string strEl = el.ToString();
string[] words = strEl.Split(' ');
foreach (string word in words)
{
    if (word.StartsWith("LoginName"))
    {
        strEl = word;
        int first = strEl.IndexOf("\"");
        int last = strEl.LastIndexOf("\"");
        string str2 = strEl.Substring(first + 1, last - first - 1); 
        //str2 = "dn1\jdiaz"
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top