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); }
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.
The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With